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