wikiparser-node 0.9.2-b → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/README.md +40 -0
  2. package/config/.schema.json +134 -0
  3. package/config/default.json +832 -0
  4. package/config/llwiki.json +630 -0
  5. package/config/moegirl.json +729 -0
  6. package/config/zhwiki.json +1269 -0
  7. package/i18n/zh-hans.json +1 -0
  8. package/i18n/zh-hant.json +1 -0
  9. package/index.js +333 -0
  10. package/lib/element.js +611 -0
  11. package/lib/node.js +770 -0
  12. package/lib/ranges.js +130 -0
  13. package/lib/text.js +263 -0
  14. package/lib/title.js +83 -0
  15. package/mixin/attributeParent.js +117 -0
  16. package/mixin/fixedToken.js +40 -0
  17. package/mixin/hidden.js +21 -0
  18. package/mixin/singleLine.js +31 -0
  19. package/mixin/sol.js +54 -0
  20. package/package.json +49 -47
  21. package/parser/brackets.js +126 -0
  22. package/parser/commentAndExt.js +59 -0
  23. package/parser/converter.js +46 -0
  24. package/parser/externalLinks.js +33 -0
  25. package/parser/hrAndDoubleUnderscore.js +49 -0
  26. package/parser/html.js +42 -0
  27. package/parser/links.js +94 -0
  28. package/parser/list.js +59 -0
  29. package/parser/magicLinks.js +41 -0
  30. package/parser/quotes.js +64 -0
  31. package/parser/selector.js +177 -0
  32. package/parser/table.js +114 -0
  33. package/src/arg.js +207 -0
  34. package/src/atom/hidden.js +13 -0
  35. package/src/atom/index.js +43 -0
  36. package/src/attribute.js +470 -0
  37. package/src/attributes.js +453 -0
  38. package/src/charinsert.js +97 -0
  39. package/src/converter.js +176 -0
  40. package/src/converterFlags.js +284 -0
  41. package/src/converterRule.js +256 -0
  42. package/src/extLink.js +180 -0
  43. package/src/gallery.js +149 -0
  44. package/src/hasNowiki/index.js +44 -0
  45. package/src/hasNowiki/pre.js +40 -0
  46. package/src/heading.js +134 -0
  47. package/src/html.js +254 -0
  48. package/src/imageParameter.js +303 -0
  49. package/src/imagemap.js +199 -0
  50. package/src/imagemapLink.js +41 -0
  51. package/src/index.js +932 -0
  52. package/src/link/category.js +44 -0
  53. package/src/link/file.js +287 -0
  54. package/src/link/galleryImage.js +120 -0
  55. package/src/link/index.js +388 -0
  56. package/src/magicLink.js +149 -0
  57. package/src/nested/choose.js +24 -0
  58. package/src/nested/combobox.js +23 -0
  59. package/src/nested/index.js +93 -0
  60. package/src/nested/references.js +23 -0
  61. package/src/nowiki/comment.js +71 -0
  62. package/src/nowiki/dd.js +59 -0
  63. package/src/nowiki/doubleUnderscore.js +56 -0
  64. package/src/nowiki/hr.js +41 -0
  65. package/src/nowiki/index.js +56 -0
  66. package/src/nowiki/list.js +16 -0
  67. package/src/nowiki/noinclude.js +28 -0
  68. package/src/nowiki/quote.js +69 -0
  69. package/src/onlyinclude.js +64 -0
  70. package/src/paramTag/index.js +89 -0
  71. package/src/paramTag/inputbox.js +35 -0
  72. package/src/parameter.js +239 -0
  73. package/src/syntax.js +91 -0
  74. package/src/table/index.js +983 -0
  75. package/src/table/td.js +338 -0
  76. package/src/table/tr.js +319 -0
  77. package/src/tagPair/ext.js +145 -0
  78. package/src/tagPair/include.js +50 -0
  79. package/src/tagPair/index.js +126 -0
  80. package/src/transclude.js +843 -0
  81. package/tool/index.js +1202 -0
  82. package/util/base.js +17 -0
  83. package/util/debug.js +73 -0
  84. package/util/diff.js +76 -0
  85. package/util/lint.js +55 -0
  86. package/util/string.js +126 -0
  87. package/bundle/bundle.min.js +0 -38
  88. package/extensions/editor.css +0 -62
  89. package/extensions/editor.js +0 -328
  90. package/extensions/ui.css +0 -119
package/src/index.js ADDED
@@ -0,0 +1,932 @@
1
+ 'use strict';
2
+
3
+ // PHP解析器的步骤:
4
+ // -1. 替换签名和`{{subst:}}`,参见Parser::preSaveTransform;这在revision中不可能保留,可以跳过
5
+ // 0. 移除特定字符`\0`和`\x7F`,参见Parser::parse
6
+ // 1. 注释/扩展标签('<'相关),参见Preprocessor_Hash::buildDomTreeArrayFromText和Sanitizer::decodeTagAttributes
7
+ // 2. 模板/模板变量/标题,注意rightmost法则,以及`-{`和`[[`可以破坏`{{`或`{{{`语法,
8
+ // 参见Preprocessor_Hash::buildDomTreeArrayFromText
9
+ // 3. HTML标签(允许不匹配),参见Sanitizer::internalRemoveHtmlTags
10
+ // 4. 表格,参见Parser::handleTables
11
+ // 5. 水平线、状态开关和余下的标题,参见Parser::internalParse
12
+ // 6. 内链,含文件和分类,参见Parser::handleInternalLinks2
13
+ // 7. `'`,参见Parser::doQuotes
14
+ // 8. 外链,参见Parser::handleExternalLinks
15
+ // 9. ISBN、RFC(未来将废弃,不予支持)和自由外链,参见Parser::handleMagicLinks
16
+ // 10. 段落和列表,参见BlockLevelPass::execute
17
+ // 11. 转换,参见LanguageConverter::recursiveConvertTopLevel
18
+
19
+ // \0\d+.\x7F标记Token:
20
+ // e: ExtToken
21
+ // a: AttributeToken
22
+ // c: CommentToken、NoIncludeToken和IncludeToken
23
+ // !: `{{!}}`专用
24
+ // {: `{{(!}}`专用
25
+ // }: `{{!)}}`专用
26
+ // -: `{{!-}}`专用
27
+ // +: `{{!!}}`专用
28
+ // ~: `{{=}}`专用
29
+ // s: `{{{|subst:}}}`
30
+ // m: `{{fullurl:}}`、`{{canonicalurl:}}`或`{{filepath:}}`
31
+ // t: ArgToken或TranscludeToken
32
+ // h: HeadingToken
33
+ // x: HtmlToken
34
+ // b: TableToken
35
+ // r: HrToken
36
+ // u: DoubleUnderscoreToken
37
+ // l: LinkToken
38
+ // q: QuoteToken
39
+ // w: ExtLinkToken
40
+ // d: ListToken
41
+ // v: ConverterToken
42
+
43
+ const {text} = require('../util/string'),
44
+ {externalUse} = require('../util/debug'),
45
+ assert = require('assert/strict'),
46
+ Ranges = require('../lib/ranges'),
47
+ Parser = require('..'),
48
+ AstElement = require('../lib/element'),
49
+ AstText = require('../lib/text');
50
+ const {MAX_STAGE, aliases} = Parser;
51
+
52
+ /**
53
+ * 所有节点的基类
54
+ * @classdesc `{childNodes: ...(AstText|Token)}`
55
+ */
56
+ class Token extends AstElement {
57
+ type = 'root';
58
+ #stage = 0; // 解析阶段,参见顶部注释。只对plain Token有意义。
59
+ #config;
60
+ // 这个数组起两个作用:1. 数组中的Token会在build时替换`/\0\d+.\x7F/`标记;2. 数组中的Token会依次执行parseOnce和build方法。
61
+ #accum;
62
+ /** @type {boolean} */ #include;
63
+ /** @type {Record<string, Ranges>} */ #acceptable;
64
+ #protectedChildren = new Ranges();
65
+
66
+ /**
67
+ * 将维基语法替换为占位符
68
+ * @param {number} n 解析阶段
69
+ * @param {boolean} include 是否嵌入
70
+ */
71
+ #parseOnce = (n = this.#stage, include = false) => {
72
+ if (n < this.#stage || !this.isPlain() || this.length === 0) {
73
+ return this;
74
+ }
75
+ switch (n) {
76
+ case 0:
77
+ if (this.type === 'root') {
78
+ this.#accum.shift();
79
+ }
80
+ this.#include = Boolean(include);
81
+ this.#parseCommentAndExt(include);
82
+ break;
83
+ case 1:
84
+ this.#parseBrackets();
85
+ break;
86
+ case 2:
87
+ this.#parseHtml();
88
+ break;
89
+ case 3:
90
+ this.#parseTable();
91
+ break;
92
+ case 4:
93
+ this.#parseHrAndDoubleUndescore();
94
+ break;
95
+ case 5:
96
+ this.#parseLinks();
97
+ break;
98
+ case 6:
99
+ this.#parseQuotes();
100
+ break;
101
+
102
+ case 7:
103
+ this.#parseExternalLinks();
104
+ break;
105
+ case 8:
106
+ this.#parseMagicLinks();
107
+ break;
108
+ case 9:
109
+ this.#parseList();
110
+ break;
111
+ case 10:
112
+ this.#parseConverter();
113
+ // no default
114
+ }
115
+ if (this.type === 'root') {
116
+ for (const token of this.#accum) {
117
+ token.getAttribute('parseOnce')(n, include);
118
+ }
119
+ }
120
+ this.#stage++;
121
+ return this;
122
+ };
123
+
124
+ /**
125
+ * 重建wikitext
126
+ * @template {string} T
127
+ * @param {string} str 半解析的字符串
128
+ * @param {T} type 返回类型
129
+ * @complexity `n`
130
+ * @returns {T extends 'string|text' ? string : (Token|AstText)[]}
131
+ */
132
+ #buildFromStr = (str, type) => {
133
+ const nodes = str.split(/[\0\x7F]/u).map((s, i) => {
134
+ if (i % 2 === 0) {
135
+ return new AstText(s);
136
+ } else if (isNaN(s.at(-1))) {
137
+ return this.#accum[Number(s.slice(0, -1))];
138
+ }
139
+ throw new Error(`解析错误!未正确标记的 Token:${s}`);
140
+ });
141
+ if (type === 'string') {
142
+ return nodes.map(String).join('');
143
+ } else if (type === 'text') {
144
+ return text(nodes);
145
+ }
146
+ return nodes;
147
+ };
148
+
149
+ /**
150
+ * 将占位符替换为子Token
151
+ * @complexity `n`
152
+ */
153
+ #build = () => {
154
+ this.#stage = MAX_STAGE;
155
+ const {length, firstChild} = this,
156
+ str = String(firstChild);
157
+ if (length === 1 && firstChild.type === 'text' && str.includes('\0')) {
158
+ this.replaceChildren(...this.#buildFromStr(str));
159
+ this.normalize();
160
+ if (this.type === 'root') {
161
+ for (const token of this.#accum) {
162
+ token.getAttribute('build')();
163
+ }
164
+ }
165
+ }
166
+ };
167
+
168
+ /**
169
+ * 保护部分子节点不被移除
170
+ * @param {...string|number|Range} args 子节点范围
171
+ */
172
+ #protectChildren = (...args) => {
173
+ this.#protectedChildren.push(...new Ranges(args));
174
+ };
175
+
176
+ /** 所有图片,包括图库 */
177
+ get images() {
178
+ return this.querySelectorAll('file, gallery-image, imagemap-image');
179
+ }
180
+
181
+ /** 所有内链、外链和自由外链 */
182
+ get links() {
183
+ return this.querySelectorAll('link, ext-link, free-ext-link, image-parameter#link');
184
+ }
185
+
186
+ /** 所有模板和模块 */
187
+ get embeds() {
188
+ return this.querySelectorAll('template, magic-word#invoke');
189
+ }
190
+
191
+ /**
192
+ * @param {string} wikitext wikitext
193
+ * @param {accum} accum
194
+ * @param {acceptable} acceptable 可接受的子节点设置
195
+ */
196
+ constructor(wikitext, config = Parser.getConfig(), halfParsed = false, accum = [], acceptable = undefined) {
197
+ super();
198
+ if (typeof wikitext === 'string') {
199
+ this.insertAt(halfParsed ? wikitext : wikitext.replace(/[\0\x7F]/gu, ''));
200
+ }
201
+ this.#config = config;
202
+ this.#accum = accum;
203
+ this.setAttribute('acceptable', acceptable);
204
+ accum.push(this);
205
+ }
206
+
207
+ /**
208
+ * @override
209
+ * @template {string} T
210
+ * @param {T} key 属性键
211
+ * @returns {TokenAttribute<T>}
212
+ */
213
+ getAttribute(key) {
214
+ switch (key) {
215
+ case 'config':
216
+ return structuredClone(this.#config);
217
+ case 'accum':
218
+ return this.#accum;
219
+ case 'parseOnce':
220
+ return this.#parseOnce;
221
+ case 'buildFromStr':
222
+ return this.#buildFromStr;
223
+ case 'build':
224
+ return this.#build;
225
+ case 'include': {
226
+ if (this.#include !== undefined) {
227
+ return this.#include;
228
+ }
229
+ const root = this.getRootNode();
230
+ if (root.type === 'root' && root !== this) {
231
+ return root.getAttribute('include');
232
+ }
233
+ const includeToken = root.querySelector('include');
234
+ if (includeToken) {
235
+ return includeToken.name === 'noinclude';
236
+ }
237
+ const noincludeToken = root.querySelector('noinclude');
238
+ return Boolean(noincludeToken) && !/^<\/?noinclude(?:\s[^>]*)?\/?>$/iu.test(String(noincludeToken));
239
+ }
240
+ case 'stage':
241
+ return this.#stage;
242
+ case 'acceptable':
243
+ return this.#acceptable ? {...this.#acceptable} : undefined;
244
+ case 'protectChildren':
245
+ return this.#protectChildren;
246
+ case 'protectedChildren':
247
+ return new Ranges(this.#protectedChildren);
248
+ default:
249
+ return super.getAttribute(key);
250
+ }
251
+ }
252
+
253
+ /**
254
+ * @override
255
+ * @template {string} T
256
+ * @param {T} key 属性键
257
+ * @param {TokenAttribute<T>} value 属性值
258
+ */
259
+ setAttribute(key, value) {
260
+ switch (key) {
261
+ case 'stage':
262
+ if (this.#stage === 0 && this.type === 'root') {
263
+ this.#accum.shift();
264
+ }
265
+ this.#stage = value;
266
+ return this;
267
+ case 'acceptable': {
268
+ const /** @type {acceptable} */ acceptable = {};
269
+ if (value) {
270
+ for (const [k, v] of Object.entries(value)) {
271
+ if (k.startsWith('Stage-')) {
272
+ for (let i = 0; i <= Number(k.slice(6)); i++) {
273
+ for (const type of aliases[i]) {
274
+ acceptable[type] = new Ranges(v);
275
+ }
276
+ }
277
+ } else if (k[0] === '!') { // `!`项必须放在最后
278
+ delete acceptable[k.slice(1)];
279
+ } else {
280
+ acceptable[k] = new Ranges(v);
281
+ }
282
+ }
283
+ }
284
+ this.#acceptable = value && acceptable;
285
+ return this;
286
+ }
287
+ default:
288
+ return super.setAttribute(key, value);
289
+ }
290
+ }
291
+
292
+ /** 是否是普通节点 */
293
+ isPlain() {
294
+ return this.constructor === Token;
295
+ }
296
+
297
+ /**
298
+ * @override
299
+ * @template {string|Token} T
300
+ * @param {T} token 待插入的子节点
301
+ * @param {number} i 插入位置
302
+ * @complexity `n`
303
+ * @returns {T extends Token ? Token : AstText}
304
+ * @throws `RangeError` 不可插入的子节点
305
+ */
306
+ insertAt(token, i = this.length) {
307
+ if (typeof token === 'string') {
308
+ token = new AstText(token);
309
+ }
310
+ if (!Parser.running && this.#acceptable) {
311
+ const acceptableIndices = Object.fromEntries(
312
+ Object.entries(this.#acceptable)
313
+ .map(([str, ranges]) => [str, ranges.applyTo(this.length + 1)]),
314
+ ),
315
+ nodesAfter = this.childNodes.slice(i),
316
+ {constructor: {name: insertedName}} = token,
317
+ k = i < 0 ? i + this.length : i;
318
+ if (!acceptableIndices[insertedName].includes(k)) {
319
+ throw new RangeError(`${this.constructor.name} 的第 ${k} 个子节点不能为 ${insertedName}!`);
320
+ } else if (nodesAfter.some(({constructor: {name}}, j) => !acceptableIndices[name].includes(k + j + 1))) {
321
+ throw new Error(`${this.constructor.name} 插入新的第 ${k} 个子节点会破坏规定的顺序!`);
322
+ }
323
+ }
324
+ super.insertAt(token, i);
325
+ if (token.type === 'root') {
326
+ token.type = 'plain';
327
+ }
328
+ return token;
329
+ }
330
+
331
+ /**
332
+ * 规范化页面标题
333
+ * @param {string} title 标题(含或不含命名空间前缀)
334
+ * @param {number} defaultNs 命名空间
335
+ * @param {boolean} decode 是否需要解码
336
+ * @param {boolean} selfLink 是否允许selfLink
337
+ */
338
+ normalizeTitle(title, defaultNs = 0, halfParsed = false, decode = false, selfLink = false) {
339
+ return Parser.normalizeTitle(title, defaultNs, this.#include, this.#config, halfParsed, decode, selfLink);
340
+ }
341
+
342
+ /**
343
+ * @override
344
+ * @param {number} i 移除位置
345
+ * @returns {Token}
346
+ * @complexity `n`
347
+ * @throws `Error` 不可移除的子节点
348
+ */
349
+ removeAt(i) {
350
+ if (!Number.isInteger(i)) {
351
+ this.typeError('removeAt', 'Number');
352
+ }
353
+ const iPos = i < 0 ? i + this.length : i;
354
+ if (!Parser.running) {
355
+ const protectedIndices = this.#protectedChildren.applyTo(this.childNodes);
356
+ if (protectedIndices.includes(iPos)) {
357
+ throw new Error(`${this.constructor.name} 的第 ${i} 个子节点不可移除!`);
358
+ } else if (this.#acceptable) {
359
+ const acceptableIndices = Object.fromEntries(
360
+ Object.entries(this.#acceptable)
361
+ .map(([str, ranges]) => [str, ranges.applyTo(this.length - 1)]),
362
+ ),
363
+ nodesAfter = i === -1 ? [] : this.childNodes.slice(i + 1);
364
+ if (nodesAfter.some(({constructor: {name}}, j) => !acceptableIndices[name].includes(i + j))) {
365
+ throw new Error(`移除 ${this.constructor.name} 的第 ${i} 个子节点会破坏规定的顺序!`);
366
+ }
367
+ }
368
+ }
369
+ return super.removeAt(i);
370
+ }
371
+
372
+ /**
373
+ * 替换为同类节点
374
+ * @param {Token} token 待替换的节点
375
+ * @complexity `n`
376
+ * @throws `Error` 不存在父节点
377
+ * @throws `Error` 待替换的节点具有不同属性
378
+ */
379
+ safeReplaceWith(token) {
380
+ const {parentNode} = this;
381
+ if (!parentNode) {
382
+ throw new Error('不存在父节点!');
383
+ } else if (token.constructor !== this.constructor) {
384
+ this.typeError('safeReplaceWith', this.constructor.name);
385
+ }
386
+ try {
387
+ assert.deepEqual(token.getAttribute('acceptable'), this.#acceptable);
388
+ } catch (e) {
389
+ if (e instanceof assert.AssertionError) {
390
+ throw new Error(`待替换的 ${this.constructor.name} 带有不同的 #acceptable 属性!`);
391
+ }
392
+ throw e;
393
+ }
394
+ const i = parentNode.childNodes.indexOf(this);
395
+ super.removeAt.call(parentNode, i);
396
+ super.insertAt.call(parentNode, token, i);
397
+ if (token.type === 'root') {
398
+ token.type = 'plain';
399
+ }
400
+ const e = new Event('replace', {bubbles: true});
401
+ token.dispatchEvent(e, {position: i, oldToken: this, newToken: token});
402
+ }
403
+
404
+ /**
405
+ * 创建HTML注释
406
+ * @param {string} data 注释内容
407
+ */
408
+ createComment(data = '') {
409
+ if (typeof data === 'string') {
410
+ const CommentToken = require('./nowiki/comment');
411
+ const config = this.getAttribute('config');
412
+ return Parser.run(() => new CommentToken(data.replaceAll('-->', '--&gt;'), true, config));
413
+ }
414
+ return this.typeError('createComment', 'String');
415
+ }
416
+
417
+ /**
418
+ * 创建标签
419
+ * @param {string} tagName 标签名
420
+ * @param {{selfClosing: boolean, closing: boolean}} options 选项
421
+ * @throws `RangeError` 非法的标签名
422
+ */
423
+ createElement(tagName, {selfClosing, closing} = {}) {
424
+ if (typeof tagName !== 'string') {
425
+ this.typeError('createElement', 'String');
426
+ }
427
+ const config = this.getAttribute('config'),
428
+ include = this.getAttribute('include');
429
+ if (tagName === (include ? 'noinclude' : 'includeonly')) {
430
+ const IncludeToken = require('./tagPair/include');
431
+ return Parser.run(
432
+ () => new IncludeToken(tagName, '', undefined, selfClosing ? undefined : tagName, config),
433
+ );
434
+ } else if (config.ext.includes(tagName)) {
435
+ const ExtToken = require('./tagPair/ext');
436
+ return Parser.run(() => new ExtToken(tagName, '', '', selfClosing ? undefined : '', config));
437
+ } else if (config.html.flat().includes(tagName)) {
438
+ const HtmlToken = require('./html');
439
+ return Parser.run(() => new HtmlToken(tagName, '', closing, selfClosing, config));
440
+ }
441
+ throw new RangeError(`非法的标签名!${tagName}`);
442
+ }
443
+
444
+ /**
445
+ * 创建纯文本节点
446
+ * @param {string} data 文本内容
447
+ */
448
+ createTextNode(data = '') {
449
+ return typeof data === 'string' ? new AstText(data) : this.typeError('createComment', 'String');
450
+ }
451
+
452
+ /**
453
+ * 找到给定位置所在的节点
454
+ * @param {number} index 位置
455
+ */
456
+ caretPositionFromIndex(index) {
457
+ if (index === undefined) {
458
+ return undefined;
459
+ } else if (!Number.isInteger(index)) {
460
+ this.typeError('caretPositionFromIndex', 'Number');
461
+ }
462
+ const {length} = String(this);
463
+ if (index > length || index < -length) {
464
+ return undefined;
465
+ } else if (index < 0) {
466
+ index += length;
467
+ }
468
+ let child = this, // eslint-disable-line unicorn/no-this-assignment
469
+ acc = 0,
470
+ start = 0;
471
+ while (child.type !== 'text') {
472
+ const {childNodes} = child;
473
+ acc += child.getPadding();
474
+ for (let i = 0; acc <= index && i < childNodes.length; i++) {
475
+ const cur = childNodes[i],
476
+ {length: l} = String(cur);
477
+ acc += l;
478
+ if (acc >= index) {
479
+ child = cur;
480
+ acc -= l;
481
+ start = acc;
482
+ break;
483
+ }
484
+ acc += child.getGaps(i);
485
+ }
486
+ if (child.childNodes === childNodes) {
487
+ return {offsetNode: child, offset: index - start};
488
+ }
489
+ }
490
+ return {offsetNode: child, offset: index - start};
491
+ }
492
+
493
+ /**
494
+ * 找到给定位置所在的节点
495
+ * @param {number} x 列数
496
+ * @param {number} y 行数
497
+ */
498
+ caretPositionFromPoint(x, y) {
499
+ return this.caretPositionFromIndex(this.indexFromPos(y, x));
500
+ }
501
+
502
+ /**
503
+ * 找到给定位置所在的最外层节点
504
+ * @param {number} index 位置
505
+ * @throws `Error` 不是根节点
506
+ */
507
+ elementFromIndex(index) {
508
+ if (index === undefined) {
509
+ return undefined;
510
+ } else if (!Number.isInteger(index)) {
511
+ this.typeError('elementFromIndex', 'Number');
512
+ } else if (this.type !== 'root') {
513
+ throw new Error('elementFromIndex方法只可用于根节点!');
514
+ }
515
+ const {length} = String(this);
516
+ if (index > length || index < -length) {
517
+ return undefined;
518
+ } else if (index < 0) {
519
+ index += length;
520
+ }
521
+ const {childNodes} = this;
522
+ let acc = 0,
523
+ i = 0;
524
+ for (; acc < index && i < childNodes.length; i++) {
525
+ const {length: l} = String(childNodes[i]);
526
+ acc += l;
527
+ }
528
+ return childNodes[i && i - 1];
529
+ }
530
+
531
+ /**
532
+ * 找到给定位置所在的最外层节点
533
+ * @param {number} x 列数
534
+ * @param {number} y 行数
535
+ */
536
+ elementFromPoint(x, y) {
537
+ return this.elementFromIndex(this.indexFromPos(y, x));
538
+ }
539
+
540
+ /**
541
+ * 找到给定位置所在的所有节点
542
+ * @param {number} index 位置
543
+ */
544
+ elementsFromIndex(index) {
545
+ const offsetNode = this.caretPositionFromIndex(index)?.offsetNode;
546
+ return offsetNode && [...offsetNode.getAncestors().reverse(), offsetNode];
547
+ }
548
+
549
+ /**
550
+ * 找到给定位置所在的所有节点
551
+ * @param {number} x 列数
552
+ * @param {number} y 行数
553
+ */
554
+ elementsFromPoint(x, y) {
555
+ return this.elementsFromIndex(this.indexFromPos(y, x));
556
+ }
557
+
558
+ /**
559
+ * 判断标题是否是跨维基链接
560
+ * @param {string} title 标题
561
+ */
562
+ isInterwiki(title) {
563
+ return Parser.isInterwiki(title, this.#config);
564
+ }
565
+
566
+ /**
567
+ * 深拷贝所有子节点
568
+ * @complexity `n`
569
+ * @returns {(AstText|Token)[]}
570
+ */
571
+ cloneChildNodes() {
572
+ return this.childNodes.map(child => child.cloneNode());
573
+ }
574
+
575
+ /**
576
+ * 深拷贝节点
577
+ * @complexity `n`
578
+ * @throws `Error` 未定义复制方法
579
+ */
580
+ cloneNode() {
581
+ if (this.constructor !== Token) {
582
+ throw new Error(`未定义 ${this.constructor.name} 的复制方法!`);
583
+ }
584
+ const cloned = this.cloneChildNodes();
585
+ return Parser.run(() => {
586
+ const token = new Token(undefined, this.#config, false, [], this.#acceptable);
587
+ token.type = this.type;
588
+ token.append(...cloned);
589
+ token.getAttribute('protectChildren')(...this.#protectedChildren);
590
+ return token;
591
+ });
592
+ }
593
+
594
+ /**
595
+ * 获取全部章节
596
+ * @complexity `n`
597
+ */
598
+ sections() {
599
+ if (this.type !== 'root') {
600
+ return undefined;
601
+ }
602
+ const {childNodes} = this,
603
+ headings = [...childNodes.entries()].filter(([, {type}]) => type === 'heading')
604
+ .map(([i, {name}]) => [i, Number(name)]),
605
+ lastHeading = [-1, -1, -1, -1, -1, -1],
606
+ /** @type {(AstText|Token)[][]} */ sections = new Array(headings.length);
607
+ for (let i = 0; i < headings.length; i++) {
608
+ const [index, level] = headings[i];
609
+ for (let j = level; j < 6; j++) {
610
+ const last = lastHeading[j];
611
+ if (last >= 0) {
612
+ sections[last] = childNodes.slice(headings[last][0], index);
613
+ }
614
+ lastHeading[j] = j === level ? i : -1;
615
+ }
616
+ }
617
+ for (const last of lastHeading) {
618
+ if (last >= 0) {
619
+ sections[last] = childNodes.slice(headings[last][0]);
620
+ }
621
+ }
622
+ sections.unshift(childNodes.slice(0, headings[0]?.[0]));
623
+ return sections;
624
+ }
625
+
626
+ /**
627
+ * 获取指定章节
628
+ * @param {number} n 章节序号
629
+ * @complexity `n`
630
+ */
631
+ section(n) {
632
+ return Number.isInteger(n) ? this.sections()?.[n] : this.typeError('section', 'Number');
633
+ }
634
+
635
+ /**
636
+ * 获取指定的外层HTML标签
637
+ * @param {string|undefined} tag HTML标签名
638
+ * @returns {[Token, Token]}
639
+ * @complexity `n`
640
+ * @throws `RangeError` 非法的标签或空标签
641
+ */
642
+ findEnclosingHtml(tag) {
643
+ if (tag !== undefined && typeof tag !== 'string') {
644
+ this.typeError('findEnclosingHtml', 'String');
645
+ }
646
+ tag = tag?.toLowerCase();
647
+ if (tag !== undefined && !this.#config.html.slice(0, 2).flat().includes(tag)) {
648
+ throw new RangeError(`非法的标签或空标签:${tag}`);
649
+ }
650
+ const {parentNode} = this;
651
+ if (!parentNode) {
652
+ return undefined;
653
+ }
654
+ const {childNodes} = parentNode,
655
+ index = childNodes.indexOf(this);
656
+ let i;
657
+ for (i = index - 1; i >= 0; i--) {
658
+ const {type, name, selfClosing, closing} = childNodes[i];
659
+ if (type === 'html' && (!tag || name === tag) && selfClosing === false && closing === false) {
660
+ break;
661
+ }
662
+ }
663
+ if (i === -1) {
664
+ return parentNode.findEnclosingHtml(tag);
665
+ }
666
+ const opening = childNodes[i];
667
+ for (i = index + 1; i < childNodes.length; i++) {
668
+ const {type, name, selfClosing, closing} = childNodes[i];
669
+ if (type === 'html' && name === opening.name && selfClosing === false && closing === true) {
670
+ break;
671
+ }
672
+ }
673
+ return i === childNodes.length
674
+ ? parentNode.findEnclosingHtml(tag)
675
+ : [opening, childNodes[i]];
676
+ }
677
+
678
+ /**
679
+ * 获取全部分类
680
+ * @complexity `n`
681
+ */
682
+ getCategories() {
683
+ return this.querySelectorAll('category').map(({name, sortkey}) => [name, sortkey]);
684
+ }
685
+
686
+ /**
687
+ * 重新解析单引号
688
+ * @throws `Error` 不接受QuoteToken作为子节点
689
+ */
690
+ redoQuotes() {
691
+ const acceptable = this.getAttribute('acceptable');
692
+ if (acceptable && !acceptable.QuoteToken?.some(
693
+ range => typeof range !== 'number' && range.start === 0 && range.end === Infinity && range.step === 1,
694
+ )) {
695
+ throw new Error(`${this.constructor.name} 不接受 QuoteToken 作为子节点!`);
696
+ }
697
+ for (const quote of this.childNodes) {
698
+ if (quote.type === 'quote') {
699
+ quote.replaceWith(String(quote));
700
+ }
701
+ }
702
+ this.normalize();
703
+ /** @type {[number, AstText][]} */
704
+ const textNodes = [...this.childNodes.entries()].filter(([, {type}]) => type === 'text'),
705
+ indices = textNodes.map(([i]) => this.getRelativeIndex(i)),
706
+ token = Parser.run(() => {
707
+ const root = new Token(text(textNodes.map(([, str]) => str)), this.getAttribute('config'));
708
+ return root.setAttribute('stage', 6).parse(7);
709
+ });
710
+ for (const quote of [...token.childNodes].reverse()) {
711
+ if (quote.type === 'quote') {
712
+ const index = quote.getRelativeIndex(),
713
+ n = indices.findLastIndex(textIndex => textIndex <= index);
714
+ this.childNodes[n].splitText(index - indices[n]);
715
+ this.childNodes[n + 1].splitText(Number(quote.name));
716
+ this.removeAt(n + 1);
717
+ this.insertAt(quote, n + 1);
718
+ }
719
+ }
720
+ this.normalize();
721
+ }
722
+
723
+ /** 解析部分魔术字 */
724
+ solveConst() {
725
+ const ArgToken = require('./arg'),
726
+ ParameterToken = require('./parameter');
727
+ const targets = this.querySelectorAll('magic-word, arg'),
728
+ magicWords = new Set(['if', 'ifeq', 'switch']);
729
+ for (let i = targets.length - 1; i >= 0; i--) {
730
+ const /** @type {ArgToken} */ target = targets[i],
731
+ {type, name, default: argDefault, childNodes, length} = target;
732
+ if (type === 'arg' || type === 'magic-word' && magicWords.has(name)) {
733
+ let replace = '';
734
+ if (type === 'arg') {
735
+ replace = argDefault === false ? String(target) : argDefault;
736
+ } else if (name === 'if' && !childNodes[1].querySelector('magic-word, template')) {
737
+ replace = String(childNodes[String(childNodes[1] ?? '').trim() ? 2 : 3] ?? '').trim();
738
+ } else if (name === 'ifeq'
739
+ && !childNodes.slice(1, 3).some(child => child.querySelector('magic-word, template'))
740
+ ) {
741
+ replace = String(childNodes[
742
+ String(childNodes[1] ?? '').trim() === String(childNodes[2] ?? '') ? 3 : 4
743
+ ] ?? '').trim();
744
+ } else if (name === 'switch' && !childNodes[1].querySelector('magic-word, template')) {
745
+ const key = String(childNodes[1] ?? '').trim();
746
+ let defaultVal = '',
747
+ found = false,
748
+ transclusion = false,
749
+ j = 2;
750
+ for (; j < length; j++) {
751
+ const /** @type {ParameterToken} */ {anon, name: option, value, firstChild} = childNodes[j];
752
+ transclusion = firstChild.querySelector('magic-word, template');
753
+ if (anon) {
754
+ if (j === length - 1) {
755
+ defaultVal = value;
756
+ } else if (transclusion) {
757
+ break;
758
+ } else {
759
+ found ||= key === value;
760
+ }
761
+ } else if (transclusion) {
762
+ break;
763
+ } else if (found || option === key) {
764
+ replace = value;
765
+ break;
766
+ } else if (option.toLowerCase() === '#default') {
767
+ defaultVal = value;
768
+ }
769
+ if (j === length - 1) {
770
+ replace = defaultVal;
771
+ }
772
+ }
773
+ if (transclusion) {
774
+ continue;
775
+ }
776
+ } else {
777
+ continue;
778
+ }
779
+ target.replaceWith(replace);
780
+ }
781
+ }
782
+ }
783
+
784
+ /** 生成部分Token的`name`属性 */
785
+ afterBuild() {
786
+ if (!Parser.debugging && externalUse('afterBuild')) {
787
+ this.debugOnly('afterBuild');
788
+ } else if (this.type === 'root') {
789
+ for (const token of this.#accum) {
790
+ token.afterBuild();
791
+ }
792
+ }
793
+ }
794
+
795
+ /**
796
+ * 解析、重构、生成部分Token的`name`属性
797
+ * @param {number} n 最大解析层级
798
+ * @param {boolean} include 是否嵌入
799
+ */
800
+ parse(n = MAX_STAGE, include = false) {
801
+ if (!Number.isInteger(n)) {
802
+ this.typeError('parse', 'Number');
803
+ }
804
+ while (this.#stage < n) {
805
+ this.#parseOnce(this.#stage, include);
806
+ }
807
+ if (n) {
808
+ this.#build();
809
+ this.afterBuild();
810
+ }
811
+ return this;
812
+ }
813
+
814
+ /**
815
+ * 解析HTML注释和扩展标签
816
+ * @param {boolean} includeOnly 是否嵌入
817
+ */
818
+ #parseCommentAndExt(includeOnly) {
819
+ const parseCommentAndExt = require('../parser/commentAndExt');
820
+ this.setText(parseCommentAndExt(String(this.firstChild), this.#config, this.#accum, includeOnly));
821
+ }
822
+
823
+ /** 解析花括号 */
824
+ #parseBrackets() {
825
+ const parseBrackets = require('../parser/brackets');
826
+ const str = this.type === 'root' ? String(this.firstChild) : `\0${String(this.firstChild)}`,
827
+ parsed = parseBrackets(str, this.#config, this.#accum);
828
+ this.setText(this.type === 'root' ? parsed : parsed.slice(1));
829
+ }
830
+
831
+ /** 解析HTML标签 */
832
+ #parseHtml() {
833
+ if (this.#config.excludes.includes('html')) {
834
+ return;
835
+ }
836
+ const parseHtml = require('../parser/html');
837
+ this.setText(parseHtml(String(this.firstChild), this.#config, this.#accum));
838
+ }
839
+
840
+ /** 解析表格 */
841
+ #parseTable() {
842
+ if (this.#config.excludes.includes('table')) {
843
+ return;
844
+ }
845
+ const parseTable = require('../parser/table'),
846
+ TableToken = require('./table');
847
+ this.setText(parseTable(this, this.#config, this.#accum));
848
+ for (const table of this.#accum) {
849
+ if (table instanceof TableToken && table.type !== 'td') {
850
+ table.normalize();
851
+ const {childNodes: [, child]} = table;
852
+ if (typeof child === 'string' && child.includes('\0')) {
853
+ table.removeAt(1);
854
+ const inner = new Token(child, this.#config, true, this.#accum);
855
+ table.insertAt(inner, 1);
856
+ inner.setAttribute('stage', 4);
857
+ }
858
+ }
859
+ }
860
+ }
861
+
862
+ /** 解析\<hr\>和状态开关 */
863
+ #parseHrAndDoubleUndescore() {
864
+ if (this.#config.excludes.includes('hr')) {
865
+ return;
866
+ }
867
+ const parseHrAndDoubleUnderscore = require('../parser/hrAndDoubleUnderscore');
868
+ this.setText(parseHrAndDoubleUnderscore(this, this.#config, this.#accum));
869
+ }
870
+
871
+ /** 解析内部链接 */
872
+ #parseLinks() {
873
+ const parseLinks = require('../parser/links');
874
+ this.setText(parseLinks(String(this.firstChild), this.#config, this.#accum));
875
+ }
876
+
877
+ /** 解析单引号 */
878
+ #parseQuotes() {
879
+ if (this.#config.excludes.includes('quote')) {
880
+ return;
881
+ }
882
+ const parseQuotes = require('../parser/quotes');
883
+ const lines = String(this.firstChild).split('\n');
884
+ for (let i = 0; i < lines.length; i++) {
885
+ lines[i] = parseQuotes(lines[i], this.#config, this.#accum);
886
+ }
887
+ this.setText(lines.join('\n'));
888
+ }
889
+
890
+ /** 解析外部链接 */
891
+ #parseExternalLinks() {
892
+ if (this.#config.excludes.includes('extLink')) {
893
+ return;
894
+ }
895
+ const parseExternalLinks = require('../parser/externalLinks');
896
+ this.setText(parseExternalLinks(String(this.firstChild), this.#config, this.#accum));
897
+ }
898
+
899
+ /** 解析自由外链 */
900
+ #parseMagicLinks() {
901
+ if (this.#config.excludes.includes('magicLink')) {
902
+ return;
903
+ }
904
+ const parseMagicLinks = require('../parser/magicLinks');
905
+ this.setText(parseMagicLinks(String(this.firstChild), this.#config, this.#accum));
906
+ }
907
+
908
+ /** 解析列表 */
909
+ #parseList() {
910
+ if (this.#config.excludes.includes('list')) {
911
+ return;
912
+ }
913
+ const parseList = require('../parser/list');
914
+ const lines = String(this.firstChild).split('\n');
915
+ let i = this.type === 'root' || this.type === 'ext-inner' && this.name === 'poem' ? 0 : 1;
916
+ for (; i < lines.length; i++) {
917
+ lines[i] = parseList(lines[i], this.#config, this.#accum);
918
+ }
919
+ this.setText(lines.join('\n'));
920
+ }
921
+
922
+ /** 解析语言变体转换 */
923
+ #parseConverter() {
924
+ if (this.#config.variants?.length > 0) {
925
+ const parseConverter = require('../parser/converter');
926
+ this.setText(parseConverter(String(this.firstChild), this.#config, this.#accum));
927
+ }
928
+ }
929
+ }
930
+
931
+ Parser.classes.Token = __filename;
932
+ module.exports = Token;