@spyglassmc/mcdoc-cli 0.1.0 → 0.1.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/lib/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- #!/usr/bin/env node
1
+ #!/usr/bin/env -S ts-node --esm
2
2
  export {};
3
3
  //# sourceMappingURL=index.d.ts.map
package/lib/index.js CHANGED
@@ -1,10 +1,238 @@
1
- #!/usr/bin/env node
1
+ #!/usr/bin/env -S ts-node --esm
2
+ import { dirname, join, parse, resolve } from 'path';
3
+ import { fileURLToPath, pathToFileURL } from 'url';
4
+ import fs from 'fs-extra';
5
+ import walk from 'klaw';
6
+ import lineColumn from 'line-column';
2
7
  import yargs from 'yargs';
3
8
  import { hideBin } from 'yargs/helpers';
4
- await yargs(hideBin(process.argv))
5
- .scriptName('mcdoc')
6
- .command('generate-locale', 'Generate the default locale', () => {
7
- console.log('Generating locale...');
9
+ import { ConfigService, fileUtil, Service, VanillaConfig, } from '@spyglassmc/core';
10
+ import { NodeJsExternals } from '@spyglassmc/core/lib/nodejs.js';
11
+ import * as je from '@spyglassmc/java-edition';
12
+ import * as mcdoc from '@spyglassmc/mcdoc';
13
+ const parentPath = dirname(fileURLToPath(import.meta.url));
14
+ const cacheRoot = join(parentPath, 'cache');
15
+ const CLI = yargs(hideBin(process.argv));
16
+ await CLI.scriptName('mcdoc')
17
+ .command('generate [source]', 'Generate JSON files', () => CLI.positional('source', {
18
+ describe: 'path to directory containing mcdoc source',
19
+ type: 'string',
20
+ default: '.',
21
+ }).options({
22
+ 'locale': {
23
+ alias: 'l',
24
+ description: 'en-us language key-value store of all doc comments',
25
+ default: false,
26
+ },
27
+ 'module': {
28
+ alias: 'm',
29
+ description: 'file tree mirroring definitions; to optimize for web',
30
+ default: false,
31
+ },
32
+ 'pretty': {
33
+ alias: 'p',
34
+ description: 'pretty printed variants',
35
+ default: false,
36
+ },
37
+ 'verbose': {
38
+ alias: 'v',
39
+ default: false,
40
+ },
41
+ 'dry': {
42
+ alias: 'd',
43
+ description: 'will not write to disk',
44
+ default: false,
45
+ },
46
+ }).boolean('locale').boolean('module').boolean('pretty').boolean('verbose').boolean('dry'), async (args) => {
47
+ const include = [];
48
+ if (args.locale)
49
+ include.push('locales');
50
+ if (args.module)
51
+ include.push('modules');
52
+ console.info(`Generating JSON files${args.locale || args.module
53
+ ? `, including ${include.join(', ')}`
54
+ : ''}`);
55
+ const logger = {
56
+ log: (...log_args) => args.verbose ? console.log(...log_args) : false,
57
+ warn: (...log_args) => console.warn(...log_args),
58
+ error: (...log_args) => console.error(...log_args),
59
+ info: (...log_args) => args.verbose ? console.info(...log_args) : false,
60
+ trace: (message, ...params) => console.trace(message, ...params),
61
+ };
62
+ const projectPath = resolve(parentPath, args.source);
63
+ await fileUtil.ensureDir(NodeJsExternals, projectPath);
64
+ const service = new Service({
65
+ logger,
66
+ project: {
67
+ cacheRoot: fileUtil.ensureEndingSlash(pathToFileURL(cacheRoot).toString()),
68
+ defaultConfig: ConfigService.merge(VanillaConfig, {
69
+ env: { dependencies: [] },
70
+ }),
71
+ externals: NodeJsExternals,
72
+ initializers: [mcdoc.initialize, je.initialize],
73
+ projectRoot: fileUtil.ensureEndingSlash(pathToFileURL(projectPath).toString()),
74
+ },
75
+ });
76
+ await service.project.ready();
77
+ await service.project.cacheService.save();
78
+ const out = 'out';
79
+ if (args.dry !== true) {
80
+ await fs.ensureDir(out);
81
+ }
82
+ const symbols = [];
83
+ const internal_locales = {};
84
+ const locales = {};
85
+ let errors = 0;
86
+ for await (const doc_file of walk(projectPath)) {
87
+ if (doc_file.path.endsWith('.mcdoc')) {
88
+ const DocumentUri = pathToFileURL(doc_file.path).toString();
89
+ const doc_contents = await fs.readFile(doc_file.path, 'utf-8');
90
+ await service.project.onDidOpen(DocumentUri, 'mcdoc', 0, doc_contents);
91
+ const check = await service.project.ensureClientManagedChecked(DocumentUri);
92
+ if (check && check.doc && check.node) {
93
+ const { doc, node } = check;
94
+ const path = parse(fileURLToPath(doc.uri));
95
+ const resource = join(path.dir.replace(`${projectPath}`, ''), path.name).replace(/^\//, '');
96
+ logger.info(`parsing ${resource}\n`);
97
+ if (node.children[0]) {
98
+ const children = node.children;
99
+ function flattenChild(parent, self, _parent, _child) {
100
+ const child = {};
101
+ let known_error = false;
102
+ /* @ts-ignore */
103
+ child.self = self;
104
+ /* @ts-ignore */
105
+ if (_child.parent)
106
+ child.parent = parent;
107
+ /* @ts-ignore */
108
+ if (_child.parentMap)
109
+ child.parentMap = parent;
110
+ if (_child.children) {
111
+ child.children = [];
112
+ for (const [i, __child] of Object.entries(_child.children)) {
113
+ /* @ts-ignore */
114
+ child.children[Number(i)] = flattenChild(self, `${self}[${i}]`, _child, __child);
115
+ }
116
+ }
117
+ child.type = _child.type;
118
+ if (Object.hasOwn(_child, 'isOptional')) {
119
+ /* @ts-ignore */
120
+ child.isOptional = _child.isOptional;
121
+ }
122
+ if (Object.hasOwn(_child, 'colorTokenType')) {
123
+ /* @ts-ignore */
124
+ child.colorTokenType = _child.colorTokenType;
125
+ }
126
+ /* @ts-ignore */
127
+ if (Object.hasOwn(_child, 'value')) {
128
+ /* @ts-ignore */
129
+ child.value = _child.value;
130
+ if (internal_locales[parent]) {
131
+ locales[`mcdoc.${resource.replace(/\//g, '.')}.${child.value}`] = internal_locales[parent].join('\n');
132
+ delete internal_locales[parent];
133
+ }
134
+ }
135
+ if (child.type === 'mcdoc:struct/map_key' &&
136
+ internal_locales[parent]) {
137
+ locales[`mcdoc.${resource.replace(/\//g, '.')}.map_key`] = internal_locales[parent].join('\n');
138
+ delete internal_locales[parent];
139
+ }
140
+ if (Object.hasOwn(_child, 'comment')) {
141
+ /* @ts-ignore */
142
+ const comment = _child.comment.trim();
143
+ child.comment = comment;
144
+ if (!args.dry && args.locale &&
145
+ _parent?.type === 'mcdoc:doc_comments') {
146
+ const key = parent.replace(/\[\d+\]$/, '');
147
+ if (!internal_locales.key) {
148
+ internal_locales[key] = [];
149
+ }
150
+ internal_locales[key].push(comment);
151
+ }
152
+ else if (comment.startsWith('/ ')) {
153
+ child.type = 'error';
154
+ console.warn(`known error: orphaned dispatch comment`);
155
+ known_error = true;
156
+ }
157
+ }
158
+ if (_child.hover)
159
+ child.hover = _child.hover;
160
+ if (_child.color)
161
+ child.color = _child.color;
162
+ if (child.type !== 'error')
163
+ return child;
164
+ else {
165
+ errors++;
166
+ const lc = lineColumn(doc_contents);
167
+ function range(range) {
168
+ const start = lc.fromIndex(range.start);
169
+ const end = lc.fromIndex(range.end);
170
+ return `L${start?.line}${start?.col ? `:C${start?.col}` : ''} -> L${end?.line}${end?.col ? `:C${end?.col}` : ''}`;
171
+ }
172
+ if (!known_error) {
173
+ console.warn(`mcdoc error(s):`);
174
+ /* @ts-ignore */
175
+ if (_child.parent?.parserErrors.length !== 0) {
176
+ console.warn(' parser:');
177
+ /* @ts-ignore */
178
+ _child.parent?.parserErrors.forEach(error => {
179
+ console.warn(` ${error.message}\n Location: ${range(error.range)}. Severity ${error.severity}.`);
180
+ });
181
+ }
182
+ /* @ts-ignore */
183
+ if (_child.parent?.binderErrors.length !== 0) {
184
+ console.warn(' binder:');
185
+ /* @ts-ignore */
186
+ _child.parent?.binderErrors.forEach(error => {
187
+ console.warn(` ${error.message}\n Location: ${range(error.range)}. Severity ${error.severity}.`);
188
+ });
189
+ }
190
+ }
191
+ console.warn(`error @ ${doc_file.path}\n\n`);
192
+ return false;
193
+ }
194
+ }
195
+ children.forEach((child, i) => {
196
+ /* @ts-ignore */
197
+ children[i] = flattenChild(resource, `${resource}.[${i}]`, undefined, child);
198
+ });
199
+ const symbol = {
200
+ resource,
201
+ children,
202
+ };
203
+ symbols.push(symbol);
204
+ if (!args.dry && args.module) {
205
+ const dir = parse(join(out, 'module', resource)).dir;
206
+ if (dir !== '')
207
+ await fs.ensureDir(dir);
208
+ await fs.writeFile(join(out, 'module', `${resource}.mcdoc.json`), JSON.stringify(symbol));
209
+ if (args.pretty) {
210
+ await fs.writeFile(join(out, 'module', `${resource}.pretty.mcdoc.json`), JSON.stringify(symbol, undefined, 3));
211
+ }
212
+ }
213
+ }
214
+ }
215
+ }
216
+ }
217
+ if (!args.dry) {
218
+ await fs.writeFile(join(out, 'generated.mcdoc.json'), JSON.stringify(symbols));
219
+ if (args.pretty) {
220
+ await fs.writeFile(join(out, 'generated.pretty.mcdoc.json'), JSON.stringify(symbols, undefined, 3));
221
+ }
222
+ if (args.module) {
223
+ await fs.writeFile(join(out, 'module', 'index.json'), JSON.stringify(symbols.map(symbol => symbol.resource)));
224
+ }
225
+ if (args.locale) {
226
+ const orphaned_doc = Object.keys(internal_locales);
227
+ if (orphaned_doc.length !== 0) {
228
+ console.warn(`parsing error, ${orphaned_doc.length} orphaned doc comments or incorrectly parsed markup comments`);
229
+ console.warn(internal_locales);
230
+ }
231
+ await fs.writeFile(join(out, 'locale.en-us.json'), JSON.stringify(locales, undefined, 3));
232
+ }
233
+ }
234
+ console.log(`Generated JSON files with ${errors} errors.`);
235
+ await service.project.close();
8
236
  })
9
237
  .strict()
10
238
  .demandCommand(1)
package/package.json CHANGED
@@ -1,10 +1,18 @@
1
1
  {
2
2
  "name": "@spyglassmc/mcdoc-cli",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "type": "module",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",
7
- "author": "Misode",
7
+ "contributors": [
8
+ {
9
+ "name": "Misode"
10
+ },
11
+ {
12
+ "name": "MulverineX",
13
+ "url": "http://mulverine.dev"
14
+ }
15
+ ],
8
16
  "license": "MIT",
9
17
  "directories": {
10
18
  "test": "test/"
@@ -14,14 +22,21 @@
14
22
  },
15
23
  "scripts": {
16
24
  "release": "npm publish",
17
- "release:dry": "npm publish --dry-run"
25
+ "release:dry": "npm publish --dry-run",
26
+ "test": "rm -rf vanilla-mcdoc && rm -rf src/out && git clone https://github.com/SpyglassMC/vanilla-mcdoc && cd src && ./index.ts generate ../vanilla-mcdoc/ -p -m -l"
18
27
  },
19
28
  "dependencies": {
29
+ "fs-extra": "^11.1.1",
30
+ "klaw": "^4.1.0",
31
+ "line-column": "^1.0.2",
20
32
  "yargs": "17.6.2",
21
- "@spyglassmc/core": "0.4.1",
22
- "@spyglassmc/mcdoc": "0.3.2"
33
+ "@spyglassmc/core": "0.4.2",
34
+ "@spyglassmc/mcdoc": "0.3.3"
23
35
  },
24
36
  "devDependencies": {
37
+ "@types/fs-extra": "^11.0.2",
38
+ "@types/klaw": "^3.0.4",
39
+ "@types/line-column": "^1.0.0",
25
40
  "@types/node": "18.11.17",
26
41
  "@types/yargs": "17.0.17"
27
42
  },