forked from quisquous/cactbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
regexes.ts
476 lines (420 loc) · 15.5 KB
/
regexes.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
import { NetParams } from '../types/net_props';
import { CactbotBaseRegExp } from '../types/net_trigger';
import logDefinitions, { LogDefinitionTypes, ParseHelperFields } from './netlog_defs';
const separator = ':';
const matchDefault = '[^:]*';
const matchWithColonsDefault = '(?:[^:]|: )*?';
const fieldsWithPotentialColons = ['effect', 'ability'];
const defaultParams = <
T extends keyof typeof logDefinitions,
>(type: T, include?: string[]): Partial<ParseHelperFields<T>> => {
include ??= Object.keys(logDefinitions[type].fields);
const params: { [index: number]: { field: string; value?: string } } = {};
for (const [prop, index] of Object.entries(logDefinitions[type].fields)) {
if (!include.includes(prop))
continue;
const param: { field: string; value?: string } = {
field: prop,
};
if (prop === 'type')
param.value = logDefinitions[type].type;
params[index] = param;
}
return params as unknown as Partial<ParseHelperFields<T>>;
};
const parseHelper = <T extends LogDefinitionTypes>(
params: { timestamp?: string; capture?: boolean } | undefined,
defKey: T,
fields: Partial<ParseHelperFields<T>>,
): CactbotBaseRegExp<T> => {
params = params ?? {};
const validFields: string[] = [];
for (const index in fields) {
const field = fields[index];
if (field)
validFields.push(field.field);
}
Regexes.validateParams(params, defKey, ['capture', ...validFields]);
// Find the last key we care about, so we can shorten the regex if needed.
const capture = Regexes.trueIfUndefined(params.capture);
const fieldKeys = Object.keys(fields).sort((a, b) => parseInt(a) - parseInt(b));
let maxKeyStr: string;
if (capture) {
maxKeyStr = fieldKeys[fieldKeys.length - 1] ?? '0';
} else {
maxKeyStr = '0';
for (const key in fields) {
const value = fields[key] ?? {};
if (typeof value !== 'object')
continue;
const fieldName = fields[key]?.field;
if (fieldName && fieldName in params)
maxKeyStr = key;
}
}
const maxKey = parseInt(maxKeyStr);
// Special case for Ability to handle aoe and non-aoe.
const abilityMessageType =
`(?:${logDefinitions.Ability.messageType}|${logDefinitions.NetworkAOEAbility.messageType})`;
const abilityHexCode = '(?:15|16)';
// Build the regex from the fields.
const prefix = defKey !== 'Ability' ? logDefinitions[defKey].messageType : abilityMessageType;
const hexCode = defKey !== 'Ability'
? `00${parseInt(logDefinitions[defKey].type).toString(16)}`.slice(-2).toUpperCase()
: abilityHexCode;
let str = '';
if (capture)
str += `(?<timestamp>\\y{Timestamp}) ${prefix} (?<type>${hexCode})`;
else
str += `\\y{Timestamp} ${prefix} ${hexCode}`;
let lastKey = 1;
for (const keyStr in fields) {
const fieldName = fields[keyStr]?.field;
// Regex handles these manually above in the `str` initialization.
if (fieldName === 'timestamp' || fieldName === 'type')
continue;
const key = parseInt(keyStr);
// Fill in blanks.
const missingFields = key - lastKey - 1;
if (missingFields === 1)
str += `${separator}${matchDefault}`;
else if (missingFields > 1)
str += `(?:${separator}${matchDefault}){${missingFields}}`;
lastKey = key;
str += separator;
const value = fields[keyStr];
if (typeof value !== 'object')
throw new Error(`${defKey}: invalid value: ${JSON.stringify(value)}`);
const fieldDefault = fieldName && fieldsWithPotentialColons.includes(fieldName)
? matchWithColonsDefault
: matchDefault;
const fieldValue = fields[keyStr]?.value?.toString() ?? fieldDefault;
if (fieldName) {
str += Regexes.maybeCapture(
// more accurate type instead of `as` cast
// maybe this function needs a refactoring
capture,
fieldName,
(params as { [s: string]: string })[fieldName],
fieldValue,
);
} else {
str += fieldValue;
}
// Stop if we're not capturing and don't care about future fields.
if (key >= maxKey)
break;
}
str += '(?:$|:)';
return Regexes.parse(str) as CactbotBaseRegExp<T>;
};
export default class Regexes {
/**
* matches: https://github.com/quisquous/cactbot/blob/main/docs/LogGuide.md#14-networkstartscasting
*/
static startsUsing(params?: NetParams['StartsUsing']): CactbotBaseRegExp<'StartsUsing'> {
return parseHelper(params, 'StartsUsing', defaultParams('StartsUsing'));
}
/**
* matches: https://github.com/quisquous/cactbot/blob/main/docs/LogGuide.md#15-networkability
* matches: https://github.com/quisquous/cactbot/blob/main/docs/LogGuide.md#16-networkaoeability
*/
static ability(params?: NetParams['Ability']): CactbotBaseRegExp<'Ability'> {
return parseHelper(params, 'Ability', {
...defaultParams('Ability', [
'type',
'timestamp',
'sourceId',
'source',
'id',
'ability',
'targetId',
'target',
]),
});
}
/**
* matches: https://github.com/quisquous/cactbot/blob/main/docs/LogGuide.md#15-networkability
* matches: https://github.com/quisquous/cactbot/blob/main/docs/LogGuide.md#16-networkaoeability
*/
static abilityFull(params?: NetParams['Ability']): CactbotBaseRegExp<'Ability'> {
return parseHelper(params, 'Ability', defaultParams('Ability'));
}
/**
* matches: https://github.com/quisquous/cactbot/blob/main/docs/LogGuide.md#1b-networktargeticon-head-markers
*/
static headMarker(params?: NetParams['HeadMarker']): CactbotBaseRegExp<'HeadMarker'> {
return parseHelper(params, 'HeadMarker', defaultParams('HeadMarker'));
}
/**
* matches: https://github.com/quisquous/cactbot/blob/main/docs/LogGuide.md#03-addcombatant
*/
static addedCombatant(params?: NetParams['AddedCombatant']): CactbotBaseRegExp<'AddedCombatant'> {
return parseHelper(
params,
'AddedCombatant',
defaultParams('AddedCombatant', [
'type',
'timestamp',
'id',
'name',
]),
);
}
/**
* matches: https://github.com/quisquous/cactbot/blob/main/docs/LogGuide.md#03-addcombatant
*/
static addedCombatantFull(
params?: NetParams['AddedCombatant'],
): CactbotBaseRegExp<'AddedCombatant'> {
return parseHelper(params, 'AddedCombatant', defaultParams('AddedCombatant'));
}
/**
* matches: https://github.com/quisquous/cactbot/blob/main/docs/LogGuide.md#04-removecombatant
*/
static removingCombatant(
params?: NetParams['RemovedCombatant'],
): CactbotBaseRegExp<'RemovedCombatant'> {
return parseHelper(params, 'RemovedCombatant', defaultParams('RemovedCombatant'));
}
/**
* matches: https://github.com/quisquous/cactbot/blob/main/docs/LogGuide.md#1a-networkbuff
*/
static gainsEffect(params?: NetParams['GainsEffect']): CactbotBaseRegExp<'GainsEffect'> {
return parseHelper(params, 'GainsEffect', defaultParams('GainsEffect'));
}
/**
* Prefer gainsEffect over this function unless you really need extra data.
* matches: https://github.com/quisquous/cactbot/blob/main/docs/LogGuide.md#26-networkstatuseffects
*/
static statusEffectExplicit(
params?: NetParams['StatusEffect'],
): CactbotBaseRegExp<'StatusEffect'> {
return parseHelper(params, 'StatusEffect', defaultParams('StatusEffect'));
}
/**
* matches: https://github.com/quisquous/cactbot/blob/main/docs/LogGuide.md#1e-networkbuffremove
*/
static losesEffect(params?: NetParams['LosesEffect']): CactbotBaseRegExp<'LosesEffect'> {
return parseHelper(params, 'LosesEffect', defaultParams('LosesEffect'));
}
/**
* matches: https://github.com/quisquous/cactbot/blob/main/docs/LogGuide.md#23-networktether
*/
static tether(params?: NetParams['Tether']): CactbotBaseRegExp<'Tether'> {
return parseHelper(params, 'Tether', defaultParams('Tether'));
}
/**
* 'target' was defeated by 'source'
* matches: https://github.com/quisquous/cactbot/blob/main/docs/LogGuide.md#19-networkdeath
*/
static wasDefeated(params?: NetParams['WasDefeated']): CactbotBaseRegExp<'WasDefeated'> {
return parseHelper(params, 'WasDefeated', defaultParams('WasDefeated'));
}
/**
* matches: https://github.com/quisquous/cactbot/blob/main/docs/LogGuide.md#00-logline
*/
static echo(params?: NetParams['GameLog']): CactbotBaseRegExp<'GameLog'> {
if (typeof params === 'undefined')
params = {};
Regexes.validateParams(
params,
'echo',
['type', 'timestamp', 'code', 'name', 'line', 'capture'],
);
params.code = '0038';
return Regexes.gameLog(params);
}
/**
* matches: https://github.com/quisquous/cactbot/blob/main/docs/LogGuide.md#00-logline
*/
static dialog(params?: NetParams['GameLog']): CactbotBaseRegExp<'GameLog'> {
if (typeof params === 'undefined')
params = {};
Regexes.validateParams(
params,
'dialog',
['type', 'timestamp', 'code', 'name', 'line', 'capture'],
);
params.code = '0044';
return Regexes.gameLog(params);
}
/**
* matches: https://github.com/quisquous/cactbot/blob/main/docs/LogGuide.md#00-logline
*/
static message(params?: NetParams['GameLog']): CactbotBaseRegExp<'GameLog'> {
if (typeof params === 'undefined')
params = {};
Regexes.validateParams(
params,
'message',
['type', 'timestamp', 'code', 'name', 'line', 'capture'],
);
params.code = '0839';
return Regexes.gameLog(params);
}
/**
* fields: code, name, line, capture
* matches: https://github.com/quisquous/cactbot/blob/main/docs/LogGuide.md#00-logline
*/
static gameLog(params?: NetParams['GameLog']): CactbotBaseRegExp<'GameLog'> {
return parseHelper(params, 'GameLog', defaultParams('GameLog'));
}
/**
* matches: https://github.com/quisquous/cactbot/blob/main/docs/LogGuide.md#00-logline
*/
static gameNameLog(params?: NetParams['GameLog']): CactbotBaseRegExp<'GameLog'> {
// Backwards compatability.
return Regexes.gameLog(params);
}
/**
* matches: https://github.com/quisquous/cactbot/blob/main/docs/LogGuide.md#0c-playerstats
*/
static statChange(params?: NetParams['PlayerStats']): CactbotBaseRegExp<'PlayerStats'> {
return parseHelper(params, 'PlayerStats', defaultParams('PlayerStats'));
}
/**
* matches: https://github.com/quisquous/cactbot/blob/main/docs/LogGuide.md#01-changezone
*/
static changeZone(params?: NetParams['ChangeZone']): CactbotBaseRegExp<'ChangeZone'> {
return parseHelper(params, 'ChangeZone', defaultParams('ChangeZone'));
}
/**
* matches: https://github.com/quisquous/cactbot/blob/main/docs/LogGuide.md#21-network6d-actor-control-lines
*/
static network6d(params?: NetParams['ActorControl']): CactbotBaseRegExp<'ActorControl'> {
return parseHelper(params, 'ActorControl', defaultParams('ActorControl'));
}
/**
* matches: https://github.com/quisquous/cactbot/blob/main/docs/LogGuide.md#22-networknametoggle
*/
static nameToggle(params?: NetParams['NameToggle']): CactbotBaseRegExp<'NameToggle'> {
return parseHelper(params, 'NameToggle', defaultParams('NameToggle'));
}
/**
* matches: https://github.com/quisquous/cactbot/blob/main/docs/LogGuide.md#28-map
*/
static map(params?: NetParams['Map']): CactbotBaseRegExp<'Map'> {
return parseHelper(params, 'Map', defaultParams('Map'));
}
/**
* matches: https://github.com/quisquous/cactbot/blob/main/docs/LogGuide.md#29-systemlogmessage
*/
static systemLogMessage(
params?: NetParams['SystemLogMessage'],
): CactbotBaseRegExp<'SystemLogMessage'> {
return parseHelper(params, 'SystemLogMessage', defaultParams('SystemLogMessage'));
}
/**
* Helper function for building named capture group
*/
static maybeCapture(
capture: boolean,
name: string,
value: string | string[] | undefined,
defaultValue?: string,
): string {
if (value === undefined)
value = defaultValue ?? matchDefault;
value = Regexes.anyOf(value);
return capture ? Regexes.namedCapture(name, value) : value;
}
static optional(str: string): string {
return `(?:${str})?`;
}
// Creates a named regex capture group named |name| for the match |value|.
static namedCapture(name: string, value: string): string {
if (name.includes('>'))
console.error('"' + name + '" contains ">".');
if (name.includes('<'))
console.error('"' + name + '" contains ">".');
return '(?<' + name + '>' + value + ')';
}
/**
* Convenience for turning multiple args into a unioned regular expression.
* anyOf(x, y, z) or anyOf([x, y, z]) do the same thing, and return (?:x|y|z).
* anyOf(x) or anyOf(x) on its own simplifies to just x.
* args may be strings or RegExp, although any additional markers to RegExp
* like /insensitive/i are dropped.
*/
static anyOf(...args: (string | string[] | RegExp)[]): string {
const anyOfArray = (array: (string | RegExp)[]): string => {
return `(?:${array.map((elem) => elem instanceof RegExp ? elem.source : elem).join('|')})`;
};
let array: (string | RegExp)[] = [];
if (args.length === 1) {
if (Array.isArray(args[0]))
array = args[0];
else if (args[0])
array = [args[0]];
else
array = [];
} else {
// TODO: more accurate type instead of `as` cast
array = args as string[];
}
return anyOfArray(array);
}
static parse(regexpString: RegExp | string | CactbotBaseRegExp<'None'>): RegExp {
const kCactbotCategories = {
Timestamp: '^.{14}',
NetTimestamp: '.{33}',
NetField: '(?:[^|]*\\|)',
LogType: '[0-9A-Fa-f]{2}',
AbilityCode: '[0-9A-Fa-f]{1,8}',
ObjectId: '[0-9A-F]{8}',
// Matches any character name (including empty strings which the FFXIV
// ACT plugin can generate when unknown).
Name: '(?:[^\\s:|]+(?: [^\\s:|]+)?|)',
// Floats can have comma as separator in FFXIV plugin output: https://github.com/ravahn/FFXIV_ACT_Plugin/issues/137
Float: '-?[0-9]+(?:[.,][0-9]+)?(?:E-?[0-9]+)?',
};
// All regexes in cactbot are case insensitive.
// This avoids headaches as things like `Vice and Vanity` turns into
// `Vice And Vanity`, especially for French and German. It appears to
// have a ~20% regex parsing overhead, but at least they work.
let modifiers = 'i';
if (regexpString instanceof RegExp) {
modifiers += (regexpString.global ? 'g' : '') +
(regexpString.multiline ? 'm' : '');
regexpString = regexpString.source;
}
regexpString = regexpString.replace(/\\y\{(.*?)\}/g, (match, group) => {
return kCactbotCategories[group as keyof typeof kCactbotCategories] || match;
});
return new RegExp(regexpString, modifiers);
}
// Like Regex.Regexes.parse, but force global flag.
static parseGlobal(regexpString: RegExp | string): RegExp {
const regex = Regexes.parse(regexpString);
let modifiers = 'gi';
if (regexpString instanceof RegExp)
modifiers += (regexpString.multiline ? 'm' : '');
return new RegExp(regex.source, modifiers);
}
static trueIfUndefined(value?: boolean): boolean {
if (typeof (value) === 'undefined')
return true;
return !!value;
}
static validateParams(
f: Readonly<{ [s: string]: unknown }>,
funcName: string,
params: Readonly<string[]>,
): void {
if (f === null)
return;
if (typeof f !== 'object')
return;
const keys = Object.keys(f);
for (let k = 0; k < keys.length; ++k) {
const key = keys[k];
if (key && !params.includes(key)) {
throw new Error(
`${funcName}: invalid parameter '${key}'. ` +
`Valid params: ${JSON.stringify(params)}`,
);
}
}
}
}