wikiparser-node 0.7.0 → 0.8.0-b

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