-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.ts
574 lines (490 loc) · 13.5 KB
/
index.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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
/* eslint n/exports-style: 0 */
import {rules, stages} from './base';
import {Shadow} from './util/debug';
import {
MAX_STAGE,
BuildMethod,
/* NOT FOR BROWSER */
classes,
} from './util/constants';
import {tidy} from './util/string';
import type {
Config,
LintError,
TokenTypes,
Parser as ParserBase,
Stage,
AST,
} from './base';
import type {Title} from './lib/title';
import type {LanguageService, QuickFixData} from './lib/lsp';
import type {Token} from './internal';
/* NOT FOR BROWSER */
import type {Chalk} from 'chalk';
import type {log} from './util/diff';
/* NOT FOR BROWSER END */
/* NOT FOR BROWSER ONLY */
import fs from 'fs';
import path from 'path';
import {
error,
/* NOT FOR BROWSER */
cmd,
info,
diff,
} from './util/diff';
/* NOT FOR BROWSER ONLY END */
declare interface Parser extends ParserBase {
rules: readonly LintError.Rule[];
/* NOT FOR BROWSER */
conversionTable: Map<string, string>;
redirects: Map<string, string>;
templateDir?: string;
templates: Map<string, string>;
warning: boolean;
debugging: boolean;
/* NOT FOR BROWSER END */
/** @private */
msg(msg: string, arg?: string): string;
/**
* Normalize page title
*
* 规范化页面标题
* @param title title (with or without the namespace prefix) / 标题(含或不含命名空间前缀)
* @param defaultNs default namespace number / 命名空间
* @param include whether to be transcluded / 是否嵌入
*/
normalizeTitle(title: string, defaultNs?: number, include?: boolean, config?: Config): Title;
/** @private */
normalizeTitle(
title: string,
defaultNs?: number,
include?: boolean,
config?: Config,
temporary?: boolean,
halfParsed?: boolean,
decode?: boolean,
selfLink?: boolean, // eslint-disable-line @typescript-eslint/unified-signatures
): Title;
parse(wikitext: string, include?: boolean, maxStage?: number | Stage | Stage[], config?: Config): Token;
/** @private */
partialParse(wikitext: string, watch: () => string, include?: boolean, config?: Config): Promise<Token>;
/**
* Create a language server
*
* 创建语言服务
* @param uri document URI / 文档标识
*/
createLanguageService(uri: object): LanguageService;
/* NOT FOR BROWSER */
/** @private */
warn: log;
/** @private */
debug: log;
/** @private */
error: log;
/** @private */
info: log;
/** @private */
log(f: Function): void;
/** @private */
require(file: string): unknown;
/** @private */
clearCache(): Promise<void>;
/**
* Check if the title is an interwiki link
*
* 是否是跨维基链接
* @param title 链接标题
*/
isInterwiki(title: string, config?: Config): RegExpExecArray | null;
/** @private */
reparse(date?: string): void;
}
/* NOT FOR BROWSER ONLY */
/**
* 从根路径require
* @param file 文件名
* @param dir 子路径
*/
const rootRequire = (file: string, dir: string): unknown => require(
path.isAbsolute(file)
? /* istanbul ignore next */ file
: path.join('..', file.includes('/') ? '' : dir, file),
);
/* NOT FOR BROWSER ONLY END */
/* NOT FOR BROWSER */
/**
* 快速规范化页面标题
* @param title 标题
*/
const normalizeTitle = (title: string): string =>
String(Parser.normalizeTitle(title, 0, false, undefined, true));
/** 重定向列表 */
class RedirectMap extends Map<string, string> {
/** @ignore */
constructor(entries?: Iterable<[string, string]>) {
super();
if (entries) {
for (const [k, v] of entries) {
this.set(k, v);
}
}
}
override set(key: string, value: string): this {
return super.set(normalizeTitle(key), normalizeTitle(value));
}
}
const promises = [Promise.resolve()];
let viewOnly = false,
redirectMap = new RedirectMap();
/* NOT FOR BROWSER END */
const Parser: Parser = { // eslint-disable-line @typescript-eslint/no-redeclare
config: 'default',
i18n: undefined,
rules,
/* NOT FOR BROWSER */
/** @implements */
get viewOnly() {
return viewOnly;
},
set viewOnly(value) {
if (viewOnly && !value) {
Shadow.rev++;
}
viewOnly = value;
},
/** @implements */
get redirects() {
return redirectMap;
},
set redirects(redirects: Map<string, string>) {
redirectMap = new RedirectMap(redirects);
},
conversionTable: new Map(),
templates: new Map(),
warning: true,
debugging: false,
/* NOT FOR BROWSER END */
/** @implements */
getConfig(config?: Config) {
/* NOT FOR BROWSER ONLY */
if (!config && typeof this.config === 'string') {
this.config = rootRequire(this.config, 'config') as Config;
/* istanbul ignore if */
if (
this.config.doubleUnderscore.length < 3
|| Array.isArray(this.config.parserFunction[1])
|| !('functionHook' in this.config)
) {
error(
`The schema (${
path.resolve(__dirname, '..', 'config', '.schema.json')
}) of parser configuration is updated.`,
);
}
/* NOT FOR BROWSER */
const {config: {conversionTable, redirects}} = this;
/* istanbul ignore if */
if (conversionTable) {
this.conversionTable = new Map(conversionTable);
}
/* istanbul ignore if */
if (redirects) {
this.redirects = new Map(redirects);
}
/* NOT FOR BROWSER END */
return this.getConfig();
}
/* NOT FOR BROWSER ONLY END */
const parserConfig = config ?? this.config as Config,
{doubleUnderscore} = parserConfig;
for (let i = 0; i < 2; i++) {
if (doubleUnderscore.length > i + 2 && doubleUnderscore[i]!.length === 0) {
doubleUnderscore[i] = Object.keys(doubleUnderscore[i + 2]!);
}
}
return {
...parserConfig,
excludes: [],
};
},
/** @implements */
msg(msg, arg = '') {
/* NOT FOR BROWSER ONLY */
if (typeof this.i18n === 'string') {
this.i18n = rootRequire(this.i18n, 'i18n') as Record<string, string>;
return this.msg(msg, arg);
}
/* NOT FOR BROWSER ONLY END */
return msg && (this.i18n?.[msg] ?? msg).replace('$1', this.msg(arg));
},
/** @implements */
normalizeTitle(
title,
defaultNs = 0,
include?: boolean,
config = Parser.getConfig(),
temporary: boolean = false,
halfParsed?: boolean,
decode: boolean = false,
selfLink: boolean = false,
) {
const {Title}: typeof import('./lib/title') = require('./lib/title');
let titleObj: Title;
if (halfParsed) {
titleObj = new Title(title, defaultNs, config, temporary, decode, selfLink);
} else {
const {Token}: typeof import('./src/index') = require('./src/index');
titleObj = Shadow.run(() => {
const root = new Token(title, config);
root.type = 'root';
root.parseOnce(0, include).parseOnce();
const t = new Title(root.toString(), defaultNs, config, temporary, decode, selfLink);
for (const key of ['main', 'fragment'] as const) {
const str = t[key];
if (str?.includes('\0')) {
const s = root.buildFromStr(str, BuildMethod.Text);
if (key === 'main') {
t.main = s;
} else {
t.setFragment(s);
}
}
}
return t;
});
}
/* NOT FOR BROWSER */
titleObj.conversionTable = this.conversionTable;
titleObj.redirects = this.redirects;
/* NOT FOR BROWSER END */
return titleObj;
},
/** @implements */
parse(wikitext, include, maxStage = MAX_STAGE, config = Parser.getConfig()) {
wikitext = tidy(wikitext);
if (typeof maxStage !== 'number') {
const types = Array.isArray(maxStage) ? maxStage : [maxStage];
maxStage = Math.max(...types.map(t => stages[t] || MAX_STAGE));
}
const {Token}: typeof import('./src/index') = require('./src/index');
const root = Shadow.run(() => {
const token = new Token(wikitext, config);
token.type = 'root';
try {
return token.parse(maxStage, include);
/* NOT FOR BROWSER ONLY */
} catch (e) /* istanbul ignore next */ {
if (e instanceof Error) {
const file = path.join(__dirname, '..', 'errors', new Date().toISOString()),
stage = token.getAttribute('stage');
for (const k in config) {
if (k.startsWith('regex') || config[k as keyof Config] instanceof Set) {
delete config[k as keyof Config];
}
}
fs.writeFileSync(file, stage === MAX_STAGE ? wikitext : token.toString());
fs.writeFileSync(`${file}.err`, e.stack!);
fs.writeFileSync(
`${file}.json`,
JSON.stringify({stage, include, config}, null, '\t'),
);
}
throw e;
}
/* NOT FOR BROWSER ONLY END */
});
/* NOT FOR BROWSER */
/* istanbul ignore if */
if (this.debugging) {
let restored = root.toString(),
process = 'parsing';
if (restored === wikitext) {
const entities = {lt: '<', gt: '>', amp: '&'};
restored = root.print().replace(
/<[^<]+?>|&([lg]t|amp);/gu,
(_, s?: keyof typeof entities) => s ? entities[s] : '',
);
process = 'printing';
}
if (restored !== wikitext) {
const {0: cur, length} = promises;
promises.unshift((async (): Promise<void> => {
await cur;
this.error(`Original wikitext is altered when ${process}!`);
return diff(wikitext, restored, length);
})());
}
}
/* NOT FOR BROWSER END */
return root;
},
/** @implements */
async partialParse(wikitext, watch, include, config = Parser.getConfig()) {
const {Token}: typeof import('./src/index') = require('./src/index');
const set = typeof setImmediate === 'function' ? setImmediate : /* istanbul ignore next */ setTimeout,
{running} = Shadow;
Shadow.running = true;
const token = new Token(tidy(wikitext), config);
token.type = 'root';
let i = 0;
await new Promise<void>(resolve => {
const /** @ignore */ check = (): void => {
if (watch() === wikitext) {
i++;
set(parseOnce, 0);
} else {
resolve();
}
},
/** @ignore */ parseOnce = (): void => {
if (i === MAX_STAGE + 1) {
token.afterBuild();
resolve();
} else {
token[i === MAX_STAGE ? 'build' : 'parseOnce'](i, include);
check();
}
};
set(parseOnce, 0);
});
Shadow.running = running;
return token;
},
/** @implements */
createLanguageService(uri: object) {
LSP: { // eslint-disable-line no-unused-labels
const mod: typeof import('./lib/lsp') = require('./lib/lsp');
const {LanguageService, tasks} = mod;
Parser.viewOnly = true;
return tasks.get(uri) ?? new LanguageService(uri);
}
},
/* NOT FOR BROWSER */
/** @implements */
warn(msg, ...args) {
/* istanbul ignore if */
if (this.warning) {
try {
const chalk: Chalk = require('chalk');
console.warn(chalk.yellow(msg), ...args);
} catch {
console.warn(msg, ...args);
}
}
},
/** @implements */
debug(msg, ...args) {
/* istanbul ignore if */
if (this.debugging) {
try {
const chalk: Chalk = require('chalk');
console.debug(chalk.blue(msg), ...args);
} catch {
console.debug(msg, ...args);
}
}
},
error,
info,
/* istanbul ignore next */
/** @implements */
log(f) {
if (typeof f === 'function') {
console.log(String(f));
}
},
/* istanbul ignore next */
/** @implements */
require(name: string): unknown {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
return Object.hasOwn(classes, name) ? require(classes[name]!)[name] : require(path.join(__dirname, name));
},
/* istanbul ignore next */
/** @implements */
async clearCache(): Promise<void> {
await cmd('npm', ['--prefix', path.join(__dirname, '..'), 'run', 'build:core']);
const entries = Object.entries(classes);
for (const [, filePath] of entries) {
try {
delete require.cache[require.resolve(filePath)];
} catch {}
}
for (const [name, filePath] of entries) {
if (name in globalThis) { // eslint-disable-line es-x/no-global-this
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, es-x/no-global-this
Object.assign(globalThis, {[name]: require(filePath)[name]});
}
}
this.info('已重新加载Parser');
},
/** @implements */
isInterwiki(title, {interwiki} = Parser.getConfig()) {
if (interwiki.length > 0) {
/^(zh|en)\s*:/diu; // eslint-disable-line @typescript-eslint/no-unused-expressions
const re = new RegExp(String.raw`^(${interwiki.join('|')})\s*:`, 'diu');
return re.exec(
title.replaceAll('_', ' ').replace(/^\s*:?\s*/u, ''),
);
}
return null;
},
/* istanbul ignore next */
/** @implements */
reparse(date = '') {
const main = fs.readdirSync(path.join(__dirname, '..', 'errors'))
.find(name => name.startsWith(date) && name.endsWith('Z'));
if (!main) {
throw new RangeError(`找不到对应时间戳的错误记录:${date}`);
}
const file = path.join(__dirname, '..', 'errors', main),
wikitext = fs.readFileSync(file, 'utf8');
const {stage, include, config}: ParsingError = require(`${file}.json`),
{Token}: typeof import('./src/index') = require('./src/index');
Shadow.run(() => {
const halfParsed = stage < MAX_STAGE,
token = new Token(halfParsed ? wikitext : tidy(wikitext), config);
token.type = 'root';
if (halfParsed) {
token.setAttribute('stage', stage);
token.parseOnce(stage, include);
} else {
token.parse(undefined, include);
}
fs.unlinkSync(file);
fs.unlinkSync(`${file}.err`);
fs.unlinkSync(`${file}.json`);
});
},
};
const def: PropertyDescriptorMap = {
default: {value: Parser},
},
enumerable = new Set([
'normalizeTitle',
'parse',
'createLanguageService',
/* NOT FOR BROWSER */
'warning',
'debugging',
'isInterwiki',
]);
for (const key in Parser) {
if (!enumerable.has(key)) {
def[key] = {enumerable: false};
}
}
Object.defineProperties(Parser, def);
// @ts-expect-error mixed export styles
export = Parser;
export default Parser;
export type {
Config,
LintError,
TokenTypes,
LanguageService,
QuickFixData,
AST,
};
export type * from './internal';