wikiparser-node 1.17.1 → 1.18.1

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.
package/dist/base.d.mts CHANGED
@@ -266,6 +266,13 @@ export interface LanguageService {
266
266
  * @param text source Wikitext / 源代码
267
267
  */
268
268
  provideDocumentSymbols(text: string): Promise<DocumentSymbol[]>;
269
+ /**
270
+ * Set the target Wikipedia
271
+ *
272
+ * 设置目标维基百科
273
+ * @param wiki Wikipedia URL / 维基百科网址
274
+ */
275
+ setTargetWikipedia(wiki: string): Promise<void>;
269
276
  }
270
277
  export interface Parser {
271
278
  config: Config | string;
@@ -275,8 +282,9 @@ export interface Parser {
275
282
  * Get the current parser configuration
276
283
  *
277
284
  * 获取当前的解析设置
285
+ * @param config unprocessed parser configuration / 未处理的解析设置
278
286
  */
279
- getConfig(): Config;
287
+ getConfig(config?: Config): Config;
280
288
  /**
281
289
  * Parse wikitext
282
290
  *
package/dist/base.d.ts CHANGED
@@ -266,6 +266,13 @@ export interface LanguageService {
266
266
  * @param text source Wikitext / 源代码
267
267
  */
268
268
  provideDocumentSymbols(text: string): Promise<DocumentSymbol[]>;
269
+ /**
270
+ * Set the target Wikipedia
271
+ *
272
+ * 设置目标维基百科
273
+ * @param wiki Wikipedia URL / 维基百科网址
274
+ */
275
+ setTargetWikipedia(wiki: string): Promise<void>;
269
276
  }
270
277
  export interface Parser {
271
278
  config: Config | string;
@@ -275,8 +282,9 @@ export interface Parser {
275
282
  * Get the current parser configuration
276
283
  *
277
284
  * 获取当前的解析设置
285
+ * @param config unprocessed parser configuration / 未处理的解析设置
278
286
  */
279
- getConfig(): Config;
287
+ getConfig(config?: Config): Config;
280
288
  /**
281
289
  * Parse wikitext
282
290
  *
@@ -0,0 +1,118 @@
1
+ "use strict";
2
+ /* eslint-disable n/no-process-exit */
3
+ var __importDefault = (this && this.__importDefault) || function (mod) {
4
+ return (mod && mod.__esModule) ? mod : { "default": mod };
5
+ };
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ const path_1 = __importDefault(require("path"));
8
+ const fs_1 = __importDefault(require("fs"));
9
+ const assert_1 = __importDefault(require("assert"));
10
+ const cm_1 = require("@bhsd/common/dist/cm");
11
+ /**
12
+ * Get the parser configuration for a Wikimedia Foundation project.
13
+ * @param site site nickname
14
+ * @param url script path
15
+ * @param force whether to overwrite the existing configuration
16
+ * @param old whether to target an older version of MediaWiki
17
+ */
18
+ exports.default = async (site, url, force, old) => {
19
+ if (!site || !url) {
20
+ console.error('Usage: npx getParserConfig <site> <script path> [force]');
21
+ process.exit(1);
22
+ }
23
+ else if (/(?:\.php|\/)$/u.test(url)) {
24
+ url = url.slice(0, url.lastIndexOf('/'));
25
+ }
26
+ let mwConfig;
27
+ const mw = {
28
+ loader: {
29
+ /** @ignore */
30
+ impl(callback) {
31
+ Object.entries(callback()[1].files).find(([k]) => k.endsWith('.data.js'))[1]();
32
+ },
33
+ /** @ignore */
34
+ implement(_, callback) {
35
+ callback();
36
+ },
37
+ },
38
+ config: {
39
+ /** @ignore */
40
+ set({ extCodeMirrorConfig }) {
41
+ mwConfig = extCodeMirrorConfig;
42
+ },
43
+ },
44
+ };
45
+ /**
46
+ * Converts an array to an object.
47
+ * @param config parser configuration
48
+ * @param config.articlePath article path
49
+ */
50
+ const arrToObj = ({ articlePath, ...obj }) => {
51
+ for (const [k, v] of Object.entries(obj)) {
52
+ if (Array.isArray(v) && v.every(x => typeof x === 'string')) {
53
+ Object.assign(obj, { [k]: Object.fromEntries(v.map(x => [x, true])) });
54
+ }
55
+ }
56
+ return obj;
57
+ };
58
+ /**
59
+ * Gets the aliases of magic words.
60
+ * @param magicwords magic words
61
+ * @param targets magic word names
62
+ */
63
+ const getAliases = (magicwords, targets) => magicwords
64
+ .filter(({ name }) => targets.has(name))
65
+ .flatMap(({ aliases }) => aliases.map(s => s.replace(/:$/u, '').toLowerCase()));
66
+ /**
67
+ * Filters out gadget-related namespaces.
68
+ * @param id namespace ID
69
+ */
70
+ const filterGadget = (id) => {
71
+ const n = Number(id);
72
+ return n < 2300 || n > 2303; // Gadget, Gadget talk, Gadget definition, Gadget definition talk
73
+ };
74
+ const m = await (await fetch(`${url}/load.php?modules=ext.CodeMirror${old ? '.data' : ''}`)).text(), params = {
75
+ action: 'query',
76
+ meta: 'siteinfo',
77
+ siprop: `general|magicwords|namespaces|namespacealiases${old ? '|variables' : ''}`,
78
+ format: 'json',
79
+ formatversion: '2',
80
+ }, { query: { general: { variants }, magicwords, namespaces, namespacealiases, variables } } = await (await fetch(`${url}/api.php?${new URLSearchParams(params).toString()}`)).json();
81
+ eval(m); // eslint-disable-line no-eval
82
+ const dir = path_1.default.join('..', '..', 'config'), ns = Object.entries(namespaces).filter(([id]) => filterGadget(id))
83
+ .flatMap(([id, { name, canonical = '' }]) => [
84
+ [id, name],
85
+ ...name === canonical ? [] : [[id, canonical]],
86
+ ]), config = {
87
+ ...(0, cm_1.getParserConfig)(require(path_1.default.join(dir, 'minimum')), mwConfig),
88
+ ...(0, cm_1.getKeywords)(magicwords),
89
+ variants: (0, cm_1.getVariants)(variants),
90
+ namespaces: Object.fromEntries(ns),
91
+ nsid: Object.fromEntries([
92
+ ...ns.map(([id, canonical]) => [canonical.toLowerCase(), Number(id)]),
93
+ ...namespacealiases.filter(({ id }) => filterGadget(id)).map(({ id, alias }) => [alias.toLowerCase(), id]),
94
+ ]),
95
+ ...old && { variable: [...variables, '='] },
96
+ articlePath: '/wiki/$1',
97
+ };
98
+ config.doubleUnderscore[0] = [];
99
+ config.doubleUnderscore[1] = [];
100
+ Object.assign(config.parserFunction[0], (0, cm_1.getConfig)(magicwords, ({ name }) => name === 'msgnw'));
101
+ if ('#choose' in config.parserFunction[0]) {
102
+ delete config.parserFunction[0]['choose'];
103
+ const i = config.variable.indexOf('choose');
104
+ if (i !== -1) {
105
+ config.variable.splice(i, 1);
106
+ }
107
+ }
108
+ config.parserFunction[2] = getAliases(magicwords, new Set(['msg', 'raw']));
109
+ config.parserFunction[3] = getAliases(magicwords, new Set(['subst', 'safesubst']));
110
+ const file = path_1.default.join(__dirname, dir, `${site}.json`), exists = fs_1.default.existsSync(file);
111
+ if (exists) {
112
+ assert_1.default.deepStrictEqual(arrToObj(require(file)), arrToObj(config));
113
+ }
114
+ if (force || !exists) {
115
+ fs_1.default.writeFileSync(file, `${JSON.stringify(config, null, '\t')}\n`);
116
+ }
117
+ return config;
118
+ };
package/dist/index.js CHANGED
@@ -74,9 +74,9 @@ const Parser = {
74
74
  debugging: false,
75
75
  /* NOT FOR BROWSER END */
76
76
  /** @implements */
77
- getConfig() {
77
+ getConfig(config) {
78
78
  /* NOT FOR BROWSER ONLY */
79
- if (typeof this.config === 'string') {
79
+ if (!config && typeof this.config === 'string') {
80
80
  this.config = rootRequire(this.config, 'config');
81
81
  /* istanbul ignore if */
82
82
  if (this.config.doubleUnderscore.length < 3 || Array.isArray(this.config.parserFunction[1])) {
@@ -96,14 +96,14 @@ const Parser = {
96
96
  return this.getConfig();
97
97
  }
98
98
  /* NOT FOR BROWSER ONLY END */
99
- const { doubleUnderscore } = this.config;
99
+ const parserConfig = config ?? this.config, { doubleUnderscore } = parserConfig;
100
100
  for (let i = 0; i < 2; i++) {
101
101
  if (doubleUnderscore.length > i + 2 && doubleUnderscore[i].length === 0) {
102
102
  doubleUnderscore[i] = Object.keys(doubleUnderscore[i + 2]);
103
103
  }
104
104
  }
105
105
  return {
106
- ...this.config,
106
+ ...parserConfig,
107
107
  excludes: [],
108
108
  };
109
109
  },
@@ -5,7 +5,8 @@ import type { LanguageService as CSSLanguageService, Stylesheet } from 'vscode-c
5
5
  import type { PublicApi } from 'stylelint';
6
6
  import type { Token } from '../internal';
7
7
  export declare const jsonTags: string[];
8
- declare let jsonLSP: JSONLanguageService | undefined, cssLSP: CSSLanguageService | undefined, stylelint: Promise<PublicApi> | undefined;
8
+ declare let jsonLSP: JSONLanguageService | undefined, cssLSP: CSSLanguageService | undefined;
9
+ declare const stylelint: Promise<PublicApi | undefined>;
9
10
  export { jsonLSP, cssLSP, stylelint };
10
11
  /** embedded document */
11
12
  declare class EmbeddedDocument implements TextDocument {
@@ -10,7 +10,7 @@ const common_1 = require("@bhsd/common");
10
10
  const constants_1 = require("../util/constants");
11
11
  /* NOT FOR BROWSER END */
12
12
  exports.jsonTags = ['templatedata', 'mapframe', 'maplink'];
13
- let jsonLSP, cssLSP, stylelint;
13
+ let jsonLSP, cssLSP;
14
14
  try {
15
15
  exports.jsonLSP = jsonLSP = require('vscode-json-languageservice')
16
16
  .getLanguageService({
@@ -42,10 +42,15 @@ try {
42
42
  .getCSSLanguageService();
43
43
  }
44
44
  catch { }
45
- try {
46
- exports.stylelint = stylelint = eval('(async () => (await import("stylelint")).default)()'); // eslint-disable-line no-eval
47
- }
48
- catch { }
45
+ const stylelint = (async () => {
46
+ try {
47
+ return (await import('stylelint')).default;
48
+ }
49
+ catch {
50
+ return undefined;
51
+ }
52
+ })();
53
+ exports.stylelint = stylelint;
49
54
  /** embedded document */
50
55
  class EmbeddedDocument {
51
56
  uri = '';
package/dist/lib/lsp.d.ts CHANGED
@@ -1,16 +1,27 @@
1
1
  import Parser from '../index';
2
2
  import type { Range, Position, ColorInformation, ColorPresentation, FoldingRange, DocumentLink, Location, WorkspaceEdit, Diagnostic as DiagnosticBase, TextEdit, Hover, SignatureHelp, InlayHint, CodeAction, DocumentSymbol } from 'vscode-languageserver-types';
3
- import type { LanguageService as LanguageServiceBase, CompletionItem, SignatureData } from '../base';
4
- import type { AttributeToken } from '../internal';
3
+ import type { Config, LanguageService as LanguageServiceBase, CompletionItem, SignatureData } from '../base';
4
+ import type { Token, AttributeToken } from '../internal';
5
5
  export interface QuickFixData extends TextEdit {
6
6
  title: string;
7
7
  fix: boolean;
8
8
  }
9
9
  export declare const tasks: WeakMap<object, Parser.LanguageService>;
10
+ /**
11
+ * Check if a token is a plain attribute.
12
+ * @param token
13
+ * @param token.type
14
+ * @param token.parentNode
15
+ * @param token.length
16
+ * @param token.firstChild
17
+ * @param style whether it is a style attribute
18
+ */
19
+ export declare const isAttr: ({ type, parentNode, length, firstChild }: Token, style?: boolean) => boolean | undefined;
10
20
  /** VSCode-style language service */
11
21
  export declare class LanguageService implements LanguageServiceBase {
12
22
  #private;
13
23
  include: boolean;
24
+ lilypond: string;
14
25
  /** @param uri 任务标识 */
15
26
  constructor(uri: object);
16
27
  /** @implements */
@@ -131,4 +142,12 @@ export declare class LanguageService implements LanguageServiceBase {
131
142
  * @param text source Wikitext / 源代码
132
143
  */
133
144
  provideDocumentSymbols(text: string): Promise<DocumentSymbol[]>;
145
+ /**
146
+ * Set the target Wikipedia
147
+ *
148
+ * 设置目标维基百科
149
+ * @param wiki Wikipedia URL / 维基百科网址
150
+ * @throws `RangeError` 不是有效的维基百科网址
151
+ */
152
+ setTargetWikipedia(wiki: string): Promise<void>;
134
153
  }