@cocos/ccbuild 1.1.17 → 1.1.18

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 (48) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +37 -37
  3. package/lib/api-builder.js +1 -1
  4. package/lib/build-engine/engine-js/index.d.ts +2 -2
  5. package/lib/build-engine/engine-js/index.js +406 -406
  6. package/lib/build-engine/engine-js/rollup-plugins/external-wasm-loader.d.ts +57 -57
  7. package/lib/build-engine/engine-js/rollup-plugins/external-wasm-loader.d.ts.map +1 -1
  8. package/lib/build-engine/engine-js/rollup-plugins/external-wasm-loader.js +323 -298
  9. package/lib/build-engine/engine-js/rollup-plugins/external-wasm-loader.js.map +1 -1
  10. package/lib/build-engine/engine-js/rollup-plugins/remove-deprecated-features.d.ts +2 -2
  11. package/lib/build-engine/engine-js/rollup-plugins/remove-deprecated-features.js +37 -37
  12. package/lib/build-engine/engine-js/rollup-plugins/ts-paths.d.ts +4 -4
  13. package/lib/build-engine/engine-js/rollup-plugins/ts-paths.js +42 -42
  14. package/lib/build-engine/engine-ts/engine-builder.d.ts +57 -57
  15. package/lib/build-engine/engine-ts/engine-builder.js +631 -631
  16. package/lib/build-engine/engine-ts/field-decorator-helper.d.ts +9 -9
  17. package/lib/build-engine/engine-ts/field-decorator-helper.js +54 -54
  18. package/lib/build-engine/engine-ts/index.d.ts +2 -2
  19. package/lib/build-engine/engine-ts/index.js +36 -36
  20. package/lib/build-engine/engine-ts/plugins/external-wasm-loader.d.ts +6 -6
  21. package/lib/build-engine/engine-ts/plugins/external-wasm-loader.js +65 -65
  22. package/lib/build-engine/engine-ts/plugins/interface.d.ts +20 -20
  23. package/lib/build-engine/engine-ts/plugins/interface.js +1 -1
  24. package/lib/build-engine/index.d.ts +145 -145
  25. package/lib/build-engine/index.d.ts.map +1 -1
  26. package/lib/build-engine/index.js +167 -167
  27. package/lib/build-engine/index.js.map +1 -1
  28. package/lib/index.d.ts +4 -4
  29. package/lib/index.js +33 -33
  30. package/lib/module-resolver.d.ts +7 -7
  31. package/lib/module-resolver.js +28 -28
  32. package/lib/stats-query/config-interface.d.ts +129 -129
  33. package/lib/stats-query/config-interface.js +3 -3
  34. package/lib/stats-query/index.d.ts +183 -183
  35. package/lib/stats-query/index.js +531 -531
  36. package/lib/stats-query/path-utils.d.ts +2 -2
  37. package/lib/stats-query/path-utils.js +35 -35
  38. package/lib/transformer/babel.d.ts +5 -5
  39. package/lib/transformer/babel.js +34 -34
  40. package/lib/transformer/index.d.ts +2 -2
  41. package/lib/transformer/index.js +28 -28
  42. package/lib/utils.d.ts +4 -4
  43. package/lib/utils.js +23 -23
  44. package/package.json +1 -1
  45. package/static/helper-dynamic-constants.txt +13 -13
  46. package/static/helper-file-decorator.ts +20 -20
  47. package/static/helper-global-exporter.txt +8 -8
  48. package/static/lib.dom.d.ts +20227 -20227
@@ -1,632 +1,632 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
- return new (P || (P = Promise))(function (resolve, reject) {
28
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
- step((generator = generator.apply(thisArg, _arguments || [])).next());
32
- });
33
- };
34
- var __importDefault = (this && this.__importDefault) || function (mod) {
35
- return (mod && mod.__esModule) ? mod : { "default": mod };
36
- };
37
- Object.defineProperty(exports, "__esModule", { value: true });
38
- exports.EngineBuilder = void 0;
39
- const fs = __importStar(require("fs-extra"));
40
- const ps = __importStar(require("path"));
41
- const babel = __importStar(require("@babel/core"));
42
- // @ts-ignore
43
- const plugin_syntax_typescript_1 = __importDefault(require("@babel/plugin-syntax-typescript"));
44
- // @ts-ignore
45
- const plugin_syntax_decorators_1 = __importDefault(require("@babel/plugin-syntax-decorators"));
46
- const traverse_1 = __importDefault(require("@babel/traverse"));
47
- const stats_query_1 = require("../../stats-query");
48
- const path_utils_1 = require("../../stats-query/path-utils");
49
- const json5 = __importStar(require("json5"));
50
- const eslint_1 = require("eslint");
51
- const dedent_1 = __importDefault(require("dedent"));
52
- const glob_1 = require("glob");
53
- var t = babel.types;
54
- const field_decorator_helper_1 = require("./field-decorator-helper");
55
- const external_wasm_loader_1 = require("./plugins/external-wasm-loader");
56
- class EngineBuilder {
57
- constructor() {
58
- this._entries = [];
59
- this._entriesForPass2 = new Set();
60
- this._virtual2code = {};
61
- this._feature2NodeModule = {
62
- 'dragon-bones': '@cocos/dragonbones-js',
63
- 'physics-2d-box2d': '@cocos/box2d',
64
- 'physics-cannon': '@cocos/cannon',
65
- 'physics-physx': '@cocos/physx',
66
- 'physics-ammo': '@cocos/bullet',
67
- };
68
- this._nodeModules = [];
69
- this._virtualOverrides = {};
70
- this._buildResult = {};
71
- this._resolveExtension = ['.ts', '.js', '.json']; // not an option
72
- // TODO: for now OH global interface conflict with Rect and Path, struct
73
- // so we need to rename them.
74
- this._renameMap = {
75
- Rect: 'RectAlias',
76
- Path: 'PathAlias',
77
- struct: 'structAlias',
78
- };
79
- this._filedDecoratorHelper = new field_decorator_helper_1.FiledDecoratorHelper();
80
- this._plugins = [];
81
- this._excludeTransform = [
82
- /external\:/
83
- ];
84
- }
85
- build(options) {
86
- return __awaiter(this, void 0, void 0, function* () {
87
- const { root } = options;
88
- this._buildResult = {};
89
- const handleIdList = (idList) => {
90
- for (let id of idList) {
91
- const handleResult = this._handleId(id);
92
- this._buildResult[handleResult.file] = handleResult;
93
- }
94
- };
95
- // pass1: build ts for native engine
96
- console.log('[Build Engine]: pass1 - traverse and compile modules');
97
- console.time('pass1');
98
- this._initPlugins(options);
99
- yield this._initOptions(options);
100
- handleIdList(this._entries);
101
- console.timeEnd('pass1');
102
- // pass2: build web version for jsb type declarations
103
- console.log('[Build Engine]: pass2 - apply jsb interface info');
104
- console.time('pass2');
105
- while (this._entriesForPass2.size !== 0) {
106
- const entries2 = Array.from(this._entriesForPass2);
107
- this._entriesForPass2.clear();
108
- this._moduleOverrides = Object.entries(this._moduleOverrides).reduce((result, [k, v]) => {
109
- if (!fs.existsSync(k) || !entries2.includes(k)) {
110
- result[k] = v;
111
- }
112
- return result;
113
- }, {});
114
- handleIdList(entries2);
115
- }
116
- console.timeEnd('pass2');
117
- if (options.outDir) {
118
- for (let file in this._buildResult) {
119
- const res = this._buildResult[file];
120
- const output = ps.join(options.outDir, ps.relative(root, file));
121
- fs.outputFileSync(output, res.code, 'utf8');
122
- }
123
- // pass3: post handle to lint import
124
- console.log('[Build Engine]: pass3 - linting import statement');
125
- console.time('pass3');
126
- yield this._lintImport([
127
- (0, path_utils_1.normalizePath)(ps.join(options.outDir, '**/*.ts'))
128
- ]);
129
- console.timeEnd('pass3');
130
- this._buildIndex();
131
- yield this._copyTypes();
132
- // this._addNodeModulesDeps(); // TODO: support node modules building
133
- }
134
- return this._buildResult;
135
- });
136
- }
137
- _initPlugins(options) {
138
- this._plugins.push((0, external_wasm_loader_1.externalWasmLoaderFactory)({
139
- engineRoot: options.root,
140
- }));
141
- }
142
- _initOptions(options) {
143
- return __awaiter(this, void 0, void 0, function* () {
144
- this._options = options;
145
- const { root, flagConfig, platform, mode } = options;
146
- const statsQuery = yield stats_query_1.StatsQuery.create(root);
147
- const constantManager = statsQuery.constantManager;
148
- if (options.features) {
149
- const featureUnits = statsQuery.getUnitsOfFeatures(options.features);
150
- this._entries = featureUnits.map(fu => (0, path_utils_1.normalizePath)(statsQuery.getFeatureUnitFile(fu)));
151
- options.features.forEach(feature => {
152
- const nodeModule = this._feature2NodeModule[feature];
153
- nodeModule && this._nodeModules.push(nodeModule);
154
- });
155
- }
156
- else {
157
- const featureUnits = statsQuery.getFeatureUnits();
158
- this._entries = featureUnits.map(fu => (0, path_utils_1.normalizePath)(statsQuery.getFeatureUnitFile(fu)));
159
- this._nodeModules.push(...Object.values(this._feature2NodeModule));
160
- }
161
- this._buildTimeConstants = constantManager.genBuildTimeConstants({
162
- platform,
163
- mode,
164
- flags: flagConfig,
165
- });
166
- this._moduleOverrides = statsQuery.evaluateModuleOverrides({
167
- mode: options.mode,
168
- platform: options.platform,
169
- buildTimeConstants: this._buildTimeConstants,
170
- });
171
- this._moduleOverrides = Object.entries(this._moduleOverrides).reduce((result, [k, v]) => {
172
- result[(0, path_utils_1.normalizePath)(k)] = (0, path_utils_1.normalizePath)(v);
173
- return result;
174
- }, {});
175
- // paths in tsconfig.json
176
- const tsconfigFile = ps.join(root, './tsconfig.json');
177
- if (fs.existsSync(tsconfigFile)) {
178
- const tsconfigContent = fs.readFileSync(tsconfigFile, 'utf8');
179
- const tsconfig = json5.parse(tsconfigContent);
180
- const compilerOptions = tsconfig.compilerOptions;
181
- if (compilerOptions && compilerOptions.baseUrl && compilerOptions.paths) {
182
- for (let [key, paths] of Object.entries(compilerOptions.paths)) {
183
- this._moduleOverrides[key] = (0, path_utils_1.normalizePath)(ps.join(ps.dirname(tsconfigFile), compilerOptions.baseUrl, paths[0]));
184
- }
185
- }
186
- }
187
- this._virtual2code['internal:constants'] = constantManager.exportStaticConstants({
188
- platform,
189
- mode,
190
- flags: flagConfig,
191
- });
192
- this._virtual2code[this._filedDecoratorHelper.getModuleName()] = this._filedDecoratorHelper.genModuleSource();
193
- // TODO: resolve node modules
194
- this._virtual2code['@cocos/box2d'] = 'export {}';
195
- this._virtual2code['@cocos/bullet'] = 'export {}';
196
- this._virtual2code['@cocos/cannon'] = 'export {}';
197
- for (let virtualName in this._virtual2code) {
198
- this._virtualOverrides[virtualName] = (0, path_utils_1.normalizePath)(ps.join(root, '__virtual__', virtualName.replace(/:/g, '_'))) + '.ts';
199
- }
200
- });
201
- }
202
- _handleId(id, importer) {
203
- const resolvedId = this._resolve(id, importer);
204
- if (typeof resolvedId === 'undefined') {
205
- throw new Error(`Cannot resolve module id: ${id} ${importer ? `in file ${importer}` : ''}`);
206
- }
207
- const code = this._load(resolvedId);
208
- if (typeof code === 'undefined') {
209
- throw new Error(`Cannot load module: ${resolvedId} ${importer ? `in file ${importer}` : ''}`);
210
- }
211
- let overrideId = this._getOverrideId(id, importer);
212
- // handle output file
213
- let file = overrideId || resolvedId;
214
- if (file.endsWith('.json')) {
215
- file = file.slice(0, -5) + '.ts';
216
- }
217
- if (this._buildResult[file]) {
218
- // skip cached file
219
- return this._buildResult[file];
220
- }
221
- const transformResult = this._transform(resolvedId, code);
222
- const handleResult = this._buildResult[file] = {
223
- code: transformResult.code,
224
- file,
225
- originalId: id,
226
- resolvedId,
227
- map: transformResult.map,
228
- };
229
- transformResult.depIdList.forEach(id => {
230
- const handleResult = this._handleId(id, file);
231
- this._buildResult[handleResult.file] = handleResult;
232
- });
233
- return handleResult;
234
- }
235
- _getOverrideId(id, importer) {
236
- var _a;
237
- let overrideId;
238
- for (let p of this._plugins) {
239
- overrideId = (_a = p.transformId) === null || _a === void 0 ? void 0 : _a.call(p, id, importer);
240
- if (overrideId) {
241
- return overrideId;
242
- }
243
- }
244
- if (id in this._virtualOverrides) {
245
- overrideId = this._virtualOverrides[id];
246
- }
247
- else if (id in this._moduleOverrides) {
248
- overrideId = this._moduleOverrides[id];
249
- }
250
- else if (!ps.isAbsolute(id) && importer) {
251
- const absolutePath = this._resolveRelative(id, importer);
252
- if (absolutePath && this._moduleOverrides[absolutePath] === importer) {
253
- this._entriesForPass2.add(absolutePath); // for next pass
254
- return;
255
- }
256
- if (absolutePath && absolutePath in this._moduleOverrides) {
257
- overrideId = this._moduleOverrides[absolutePath];
258
- }
259
- }
260
- return overrideId;
261
- }
262
- _resolve(id, importer) {
263
- var _a, _b;
264
- for (let p of this._plugins) {
265
- const resolvedId = (_a = p.resolve) === null || _a === void 0 ? void 0 : _a.call(p, id, importer);
266
- if (resolvedId) {
267
- return resolvedId;
268
- }
269
- }
270
- if (!importer) {
271
- return id; // entry
272
- }
273
- else if (id in this._virtualOverrides) {
274
- return id; // virtual module does not have real fs path
275
- }
276
- else if (id in this._moduleOverrides) {
277
- return this._moduleOverrides[id];
278
- }
279
- else if (this._nodeModules.includes(id)) {
280
- return id; // node module only use bare specifier as module id
281
- }
282
- else if (ps.isAbsolute(id)) {
283
- return id;
284
- }
285
- else {
286
- const resolved = this._resolveRelative(id, importer);
287
- if (resolved) {
288
- return (_b = this._moduleOverrides[resolved]) !== null && _b !== void 0 ? _b : resolved;
289
- }
290
- }
291
- }
292
- _resolveRelative(id, importer) {
293
- const file = (0, path_utils_1.normalizePath)(ps.join(ps.dirname(importer), id));
294
- if (ps.extname(file) && fs.existsSync(file)) {
295
- return file;
296
- }
297
- // resolve extension less
298
- for (const ext of this._resolveExtension) {
299
- const fileExt = file + ext;
300
- const indexExt = (0, path_utils_1.normalizePath)(ps.join(file, 'index')) + ext;
301
- if (fs.existsSync(fileExt)) {
302
- return fileExt;
303
- }
304
- else if (fs.existsSync(indexExt)) {
305
- return indexExt;
306
- }
307
- }
308
- }
309
- _load(id) {
310
- var _a;
311
- for (let p of this._plugins) {
312
- const loadedCode = (_a = p.load) === null || _a === void 0 ? void 0 : _a.call(p, id);
313
- if (loadedCode) {
314
- return loadedCode;
315
- }
316
- }
317
- if (fs.existsSync(id)) {
318
- let code = fs.readFileSync(id, 'utf8');
319
- if (id.endsWith('.json')) {
320
- code = `export default ${code};`;
321
- }
322
- return code;
323
- }
324
- else if (this._virtualOverrides[id]) {
325
- return this._virtual2code[id];
326
- }
327
- }
328
- _transform(file, code) {
329
- file = (0, path_utils_1.normalizePath)(file);
330
- for (let ex of this._excludeTransform) {
331
- if (ex.test(file)) {
332
- return {
333
- code,
334
- depIdList: [],
335
- };
336
- }
337
- }
338
- const depIdList = [];
339
- if (ps.extname(file) === '.js') {
340
- const dtsFile = (0, path_utils_1.toExtensionLess)(file) + '.d.ts';
341
- if (fs.existsSync(dtsFile)) {
342
- depIdList.push(dtsFile); // emit the .d.ts file
343
- }
344
- }
345
- const importExportVisitor = (path) => {
346
- // @ts-ignore
347
- const source = path.node.source;
348
- if (source) {
349
- const specifier = source.value;
350
- // add dependency
351
- if (!this._nodeModules.includes(specifier)) {
352
- // don't load node modules, we post install the modules in OH project
353
- depIdList.push(specifier);
354
- }
355
- // transform import/export declaration if needed
356
- const overrideId = this._getOverrideId(specifier, file);
357
- if (overrideId) {
358
- let relativePath = (0, path_utils_1.normalizePath)(ps.relative(ps.dirname(file), overrideId));
359
- if (!relativePath.startsWith('.')) {
360
- relativePath = './' + relativePath;
361
- }
362
- if (ps.extname(relativePath) === '.ts') {
363
- relativePath = relativePath.slice(0, -3); // remove '.ts'
364
- }
365
- // traverse to transform specifier
366
- (0, traverse_1.default)(path.node, {
367
- StringLiteral(path) {
368
- path.replaceWith(babel.types.stringLiteral(relativePath));
369
- path.skip();
370
- },
371
- }, path.scope);
372
- }
373
- }
374
- const importExportSpecifier = (path) => {
375
- const name = path.node.local.name;
376
- const alias = this._renameMap[name];
377
- if (alias) {
378
- path.replaceWith(babel.types.exportSpecifier(babel.types.identifier(alias), babel.types.identifier(alias)));
379
- }
380
- };
381
- path.traverse({
382
- ExportSpecifier: importExportSpecifier,
383
- ImportSpecifier: importExportSpecifier,
384
- });
385
- };
386
- const self = this;
387
- const transformResult = babel.transformSync(code, {
388
- configFile: false,
389
- plugins: [
390
- [plugin_syntax_typescript_1.default],
391
- [plugin_syntax_decorators_1.default, {
392
- version: '2018-09',
393
- decoratorsBeforeExport: true,
394
- }],
395
- [
396
- () => {
397
- return {
398
- name: 'custom-transform',
399
- pre(file) {
400
- const pluginPass = this;
401
- (0, traverse_1.default)(file.ast, {
402
- ClassProperty(path) {
403
- const decoratorsPath = path.get('decorators');
404
- if (Array.isArray(decoratorsPath)) {
405
- const propertyValuePath = path.get('value');
406
- const helperIdentifier = self._filedDecoratorHelper.addHelper(pluginPass.file);
407
- decoratorsPath.forEach(decPath => {
408
- const expPath = decPath.get('expression');
409
- const type = expPath.node.type;
410
- if (type === 'CallExpression') {
411
- const decName = expPath.node.callee.name;
412
- const args = expPath.node.arguments;
413
- decPath.replaceWith(t.decorator(t.callExpression(helperIdentifier, [
414
- t.identifier(decName),
415
- (propertyValuePath.node ?
416
- t.arrowFunctionExpression([], propertyValuePath.node) :
417
- t.nullLiteral()),
418
- ...args
419
- ])));
420
- }
421
- else if (type === 'Identifier') {
422
- const decName = expPath.node.name;
423
- decPath.replaceWith(t.decorator(t.callExpression(helperIdentifier, [
424
- t.identifier(decName),
425
- (propertyValuePath.node ?
426
- t.arrowFunctionExpression([], propertyValuePath.node) :
427
- t.nullLiteral())
428
- ])));
429
- }
430
- });
431
- }
432
- },
433
- });
434
- },
435
- visitor: {
436
- ImportDeclaration: importExportVisitor,
437
- ExportDeclaration: importExportVisitor,
438
- // TODO: here we rename class Rect and Path
439
- CallExpression(path) {
440
- if (path.node.callee.type === 'MemberExpression') {
441
- const memberExpressionPath = path.get('callee');
442
- const objectPath = memberExpressionPath.get('object');
443
- const name = objectPath.node.name;
444
- const alias = self._renameMap[name];
445
- if (typeof alias === 'string' && path.node.callee.object.type === 'Identifier') {
446
- objectPath.replaceWith(t.identifier(alias));
447
- }
448
- // TODO: for now, OH doesn't support standard console interface,
449
- // so we need to ignore the type checking for console call expressions.
450
- else if (name === 'console') {
451
- path.node.leadingComments = [{
452
- type: 'CommentLine',
453
- value: ' @ts-ignore',
454
- }];
455
- }
456
- }
457
- else if (path.node.callee.type === 'Import') {
458
- // TODO: for now, we transform `import('./xxx/xxx.js')` into `window.__cc_module_context__.import('./xxx/xxx.js')`
459
- // we need to support import(`project://xxx`) in the future.
460
- path.replaceWith(t.callExpression(t.memberExpression(t.memberExpression(t.identifier('window'), t.identifier('__cc_module_context__')), t.identifier('import')), path.node.arguments));
461
- }
462
- },
463
- ClassDeclaration(path) {
464
- const idPath = path.get('id');
465
- const name = idPath.node.name;
466
- const alias = self._renameMap[name];
467
- if (typeof alias === 'string') {
468
- idPath.replaceWith(t.identifier(alias));
469
- }
470
- },
471
- NewExpression(path) {
472
- const calleePath = path.get('callee');
473
- // @ts-ignore
474
- const name = calleePath.node.name;
475
- if (name) {
476
- const alias = self._renameMap[name];
477
- if (typeof alias === 'string') {
478
- calleePath.replaceWith(t.identifier(alias));
479
- }
480
- }
481
- },
482
- TSTypeAnnotation(path) {
483
- // @ts-ignore
484
- const typeName = path.node.typeAnnotation.typeName;
485
- const childPath = path.get('typeAnnotation');
486
- if (typeName) {
487
- const name = typeName.name;
488
- const alias = self._renameMap[name];
489
- if (typeof alias === 'string') {
490
- path.replaceWith(t.tsTypeAnnotation({
491
- type: 'TSExpressionWithTypeArguments',
492
- expression: t.identifier(alias),
493
- }));
494
- }
495
- }
496
- else if (childPath.type === 'TSLiteralType') {
497
- const literalPath = childPath.get('literal');
498
- if (literalPath.type === 'TemplateLiteral') {
499
- path.replaceWith(t.tsTypeAnnotation(t.tsStringKeyword()));
500
- }
501
- }
502
- },
503
- Identifier(path) {
504
- const name = path.node.name;
505
- const alias = self._renameMap[name];
506
- if (typeof alias === 'string') {
507
- if (path.parent.type === 'ObjectProperty' || path.parent.type === 'TSPropertySignature') {
508
- if (path.parent.key !== path.node) {
509
- path.replaceWith(t.identifier(alias));
510
- }
511
- }
512
- else if (path.parent.type === 'MemberExpression' || path.parent.type === 'OptionalMemberExpression') {
513
- if (path.parent.property !== path.node) {
514
- path.replaceWith(t.identifier(alias));
515
- }
516
- }
517
- else if (!(path.parent.type === 'ClassMethod' && (path.parent.kind === 'get' || path.parent.kind === 'set' || path.parent.key === path.node))
518
- && path.parent.type !== 'ClassProperty') {
519
- const newIdentifier = t.identifier(alias);
520
- if (path.node.typeAnnotation) {
521
- newIdentifier.typeAnnotation = path.node.typeAnnotation;
522
- }
523
- path.replaceWith(newIdentifier);
524
- }
525
- }
526
- },
527
- }
528
- };
529
- }
530
- ]
531
- ],
532
- });
533
- return {
534
- code: transformResult === null || transformResult === void 0 ? void 0 : transformResult.code,
535
- depIdList,
536
- };
537
- }
538
- _lintImport(lintFiles, verbose = false) {
539
- return __awaiter(this, void 0, void 0, function* () {
540
- const eslint = new eslint_1.ESLint({ fix: true,
541
- cwd: __dirname,
542
- resolvePluginsRelativeTo: __dirname,
543
- useEslintrc: false,
544
- baseConfig: {
545
- parser: "@typescript-eslint/parser",
546
- plugins: ["@typescript-eslint", "unused-imports"],
547
- rules: {
548
- "@typescript-eslint/consistent-type-imports": "error",
549
- "unused-imports/no-unused-imports": "error",
550
- },
551
- } });
552
- const results = yield eslint.lintFiles(lintFiles);
553
- yield eslint_1.ESLint.outputFixes(results);
554
- if (verbose) {
555
- const formatter = yield eslint.loadFormatter();
556
- const resultText = formatter.format(results);
557
- console.log(resultText);
558
- }
559
- });
560
- }
561
- _buildIndex() {
562
- const { outDir, root } = this._options;
563
- if (outDir) {
564
- const indexFile = (0, path_utils_1.normalizePath)(ps.join(outDir, 'index.ts'));
565
- const ccFile = (0, path_utils_1.normalizePath)(ps.join(outDir, 'cc.ts'));
566
- const systemCCFile = (0, path_utils_1.normalizePath)(ps.join(outDir, 'system-cc.js'));
567
- let indexContent = '';
568
- this._entries.forEach(item => {
569
- const relative = (0, path_utils_1.normalizePath)(ps.relative(root, (0, path_utils_1.toExtensionLess)(item)));
570
- indexContent += `export * from './${relative}';\n`;
571
- });
572
- const ccContent = (0, dedent_1.default) `import * as cc from './index';
573
- // @ts-ignore
574
- window.cc_module = cc;`;
575
- const systemCCContent = (0, dedent_1.default) `System.register([], function (exports, module) {
576
- return {
577
- execute: function () {
578
- window.__cc_module_context__ = module;
579
-
580
- exports(window.cc_module);
581
- }
582
- };
583
- });
584
- `;
585
- fs.outputFileSync(indexFile, indexContent, 'utf8');
586
- fs.outputFileSync(ccFile, ccContent, 'utf8');
587
- fs.outputFileSync(systemCCFile, systemCCContent, 'utf8');
588
- }
589
- }
590
- _copyTypes() {
591
- return __awaiter(this, void 0, void 0, function* () {
592
- const { root, outDir } = this._options;
593
- if (!outDir) {
594
- return;
595
- }
596
- const dtsFiles = glob_1.glob.sync((0, path_utils_1.normalizePath)(ps.join(root, './@types/**/*.d.ts')));
597
- for (let file of dtsFiles) {
598
- const code = fs.readFileSync(file, 'utf8');
599
- const relativePath = ps.relative(root, file);
600
- const targetPath = (0, path_utils_1.normalizePath)(ps.join(outDir, relativePath));
601
- fs.outputFileSync(targetPath, code, 'utf8');
602
- }
603
- // copy lib.dom.d.ts
604
- // we use 4.2 version of typescript
605
- const originalDomDts = (0, path_utils_1.normalizePath)(ps.join(__dirname, '../../../static/lib.dom.d.ts'));
606
- const targetDomDts = (0, path_utils_1.normalizePath)(ps.join(outDir, '@types/lib.dom.d.ts'));
607
- const code = fs.readFileSync(originalDomDts, 'utf8');
608
- fs.outputFileSync(targetDomDts, code, 'utf8');
609
- });
610
- }
611
- _addNodeModulesDeps() {
612
- const { outDir } = this._options;
613
- if (!outDir) {
614
- return;
615
- }
616
- const pkgFile = (0, path_utils_1.normalizePath)(ps.join(outDir, '..', // src
617
- '..', // cocos
618
- '..', // ets
619
- '..', // main
620
- '..', // src
621
- '..', // entry
622
- 'package.json'));
623
- if (!fs.existsSync(pkgFile)) {
624
- return;
625
- }
626
- const jsonObj = fs.readJSONSync(pkgFile);
627
- console.log(jsonObj);
628
- // TODO
629
- }
630
- }
631
- exports.EngineBuilder = EngineBuilder;
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ var __importDefault = (this && this.__importDefault) || function (mod) {
35
+ return (mod && mod.__esModule) ? mod : { "default": mod };
36
+ };
37
+ Object.defineProperty(exports, "__esModule", { value: true });
38
+ exports.EngineBuilder = void 0;
39
+ const fs = __importStar(require("fs-extra"));
40
+ const ps = __importStar(require("path"));
41
+ const babel = __importStar(require("@babel/core"));
42
+ // @ts-ignore
43
+ const plugin_syntax_typescript_1 = __importDefault(require("@babel/plugin-syntax-typescript"));
44
+ // @ts-ignore
45
+ const plugin_syntax_decorators_1 = __importDefault(require("@babel/plugin-syntax-decorators"));
46
+ const traverse_1 = __importDefault(require("@babel/traverse"));
47
+ const stats_query_1 = require("../../stats-query");
48
+ const path_utils_1 = require("../../stats-query/path-utils");
49
+ const json5 = __importStar(require("json5"));
50
+ const eslint_1 = require("eslint");
51
+ const dedent_1 = __importDefault(require("dedent"));
52
+ const glob_1 = require("glob");
53
+ var t = babel.types;
54
+ const field_decorator_helper_1 = require("./field-decorator-helper");
55
+ const external_wasm_loader_1 = require("./plugins/external-wasm-loader");
56
+ class EngineBuilder {
57
+ constructor() {
58
+ this._entries = [];
59
+ this._entriesForPass2 = new Set();
60
+ this._virtual2code = {};
61
+ this._feature2NodeModule = {
62
+ 'dragon-bones': '@cocos/dragonbones-js',
63
+ 'physics-2d-box2d': '@cocos/box2d',
64
+ 'physics-cannon': '@cocos/cannon',
65
+ 'physics-physx': '@cocos/physx',
66
+ 'physics-ammo': '@cocos/bullet',
67
+ };
68
+ this._nodeModules = [];
69
+ this._virtualOverrides = {};
70
+ this._buildResult = {};
71
+ this._resolveExtension = ['.ts', '.js', '.json']; // not an option
72
+ // TODO: for now OH global interface conflict with Rect and Path, struct
73
+ // so we need to rename them.
74
+ this._renameMap = {
75
+ Rect: 'RectAlias',
76
+ Path: 'PathAlias',
77
+ struct: 'structAlias',
78
+ };
79
+ this._filedDecoratorHelper = new field_decorator_helper_1.FiledDecoratorHelper();
80
+ this._plugins = [];
81
+ this._excludeTransform = [
82
+ /external\:/
83
+ ];
84
+ }
85
+ build(options) {
86
+ return __awaiter(this, void 0, void 0, function* () {
87
+ const { root } = options;
88
+ this._buildResult = {};
89
+ const handleIdList = (idList) => {
90
+ for (let id of idList) {
91
+ const handleResult = this._handleId(id);
92
+ this._buildResult[handleResult.file] = handleResult;
93
+ }
94
+ };
95
+ // pass1: build ts for native engine
96
+ console.log('[Build Engine]: pass1 - traverse and compile modules');
97
+ console.time('pass1');
98
+ this._initPlugins(options);
99
+ yield this._initOptions(options);
100
+ handleIdList(this._entries);
101
+ console.timeEnd('pass1');
102
+ // pass2: build web version for jsb type declarations
103
+ console.log('[Build Engine]: pass2 - apply jsb interface info');
104
+ console.time('pass2');
105
+ while (this._entriesForPass2.size !== 0) {
106
+ const entries2 = Array.from(this._entriesForPass2);
107
+ this._entriesForPass2.clear();
108
+ this._moduleOverrides = Object.entries(this._moduleOverrides).reduce((result, [k, v]) => {
109
+ if (!fs.existsSync(k) || !entries2.includes(k)) {
110
+ result[k] = v;
111
+ }
112
+ return result;
113
+ }, {});
114
+ handleIdList(entries2);
115
+ }
116
+ console.timeEnd('pass2');
117
+ if (options.outDir) {
118
+ for (let file in this._buildResult) {
119
+ const res = this._buildResult[file];
120
+ const output = ps.join(options.outDir, ps.relative(root, file));
121
+ fs.outputFileSync(output, res.code, 'utf8');
122
+ }
123
+ // pass3: post handle to lint import
124
+ console.log('[Build Engine]: pass3 - linting import statement');
125
+ console.time('pass3');
126
+ yield this._lintImport([
127
+ (0, path_utils_1.normalizePath)(ps.join(options.outDir, '**/*.ts'))
128
+ ]);
129
+ console.timeEnd('pass3');
130
+ this._buildIndex();
131
+ yield this._copyTypes();
132
+ // this._addNodeModulesDeps(); // TODO: support node modules building
133
+ }
134
+ return this._buildResult;
135
+ });
136
+ }
137
+ _initPlugins(options) {
138
+ this._plugins.push((0, external_wasm_loader_1.externalWasmLoaderFactory)({
139
+ engineRoot: options.root,
140
+ }));
141
+ }
142
+ _initOptions(options) {
143
+ return __awaiter(this, void 0, void 0, function* () {
144
+ this._options = options;
145
+ const { root, flagConfig, platform, mode } = options;
146
+ const statsQuery = yield stats_query_1.StatsQuery.create(root);
147
+ const constantManager = statsQuery.constantManager;
148
+ if (options.features) {
149
+ const featureUnits = statsQuery.getUnitsOfFeatures(options.features);
150
+ this._entries = featureUnits.map(fu => (0, path_utils_1.normalizePath)(statsQuery.getFeatureUnitFile(fu)));
151
+ options.features.forEach(feature => {
152
+ const nodeModule = this._feature2NodeModule[feature];
153
+ nodeModule && this._nodeModules.push(nodeModule);
154
+ });
155
+ }
156
+ else {
157
+ const featureUnits = statsQuery.getFeatureUnits();
158
+ this._entries = featureUnits.map(fu => (0, path_utils_1.normalizePath)(statsQuery.getFeatureUnitFile(fu)));
159
+ this._nodeModules.push(...Object.values(this._feature2NodeModule));
160
+ }
161
+ this._buildTimeConstants = constantManager.genBuildTimeConstants({
162
+ platform,
163
+ mode,
164
+ flags: flagConfig,
165
+ });
166
+ this._moduleOverrides = statsQuery.evaluateModuleOverrides({
167
+ mode: options.mode,
168
+ platform: options.platform,
169
+ buildTimeConstants: this._buildTimeConstants,
170
+ });
171
+ this._moduleOverrides = Object.entries(this._moduleOverrides).reduce((result, [k, v]) => {
172
+ result[(0, path_utils_1.normalizePath)(k)] = (0, path_utils_1.normalizePath)(v);
173
+ return result;
174
+ }, {});
175
+ // paths in tsconfig.json
176
+ const tsconfigFile = ps.join(root, './tsconfig.json');
177
+ if (fs.existsSync(tsconfigFile)) {
178
+ const tsconfigContent = fs.readFileSync(tsconfigFile, 'utf8');
179
+ const tsconfig = json5.parse(tsconfigContent);
180
+ const compilerOptions = tsconfig.compilerOptions;
181
+ if (compilerOptions && compilerOptions.baseUrl && compilerOptions.paths) {
182
+ for (let [key, paths] of Object.entries(compilerOptions.paths)) {
183
+ this._moduleOverrides[key] = (0, path_utils_1.normalizePath)(ps.join(ps.dirname(tsconfigFile), compilerOptions.baseUrl, paths[0]));
184
+ }
185
+ }
186
+ }
187
+ this._virtual2code['internal:constants'] = constantManager.exportStaticConstants({
188
+ platform,
189
+ mode,
190
+ flags: flagConfig,
191
+ });
192
+ this._virtual2code[this._filedDecoratorHelper.getModuleName()] = this._filedDecoratorHelper.genModuleSource();
193
+ // TODO: resolve node modules
194
+ this._virtual2code['@cocos/box2d'] = 'export {}';
195
+ this._virtual2code['@cocos/bullet'] = 'export {}';
196
+ this._virtual2code['@cocos/cannon'] = 'export {}';
197
+ for (let virtualName in this._virtual2code) {
198
+ this._virtualOverrides[virtualName] = (0, path_utils_1.normalizePath)(ps.join(root, '__virtual__', virtualName.replace(/:/g, '_'))) + '.ts';
199
+ }
200
+ });
201
+ }
202
+ _handleId(id, importer) {
203
+ const resolvedId = this._resolve(id, importer);
204
+ if (typeof resolvedId === 'undefined') {
205
+ throw new Error(`Cannot resolve module id: ${id} ${importer ? `in file ${importer}` : ''}`);
206
+ }
207
+ const code = this._load(resolvedId);
208
+ if (typeof code === 'undefined') {
209
+ throw new Error(`Cannot load module: ${resolvedId} ${importer ? `in file ${importer}` : ''}`);
210
+ }
211
+ let overrideId = this._getOverrideId(id, importer);
212
+ // handle output file
213
+ let file = overrideId || resolvedId;
214
+ if (file.endsWith('.json')) {
215
+ file = file.slice(0, -5) + '.ts';
216
+ }
217
+ if (this._buildResult[file]) {
218
+ // skip cached file
219
+ return this._buildResult[file];
220
+ }
221
+ const transformResult = this._transform(resolvedId, code);
222
+ const handleResult = this._buildResult[file] = {
223
+ code: transformResult.code,
224
+ file,
225
+ originalId: id,
226
+ resolvedId,
227
+ map: transformResult.map,
228
+ };
229
+ transformResult.depIdList.forEach(id => {
230
+ const handleResult = this._handleId(id, file);
231
+ this._buildResult[handleResult.file] = handleResult;
232
+ });
233
+ return handleResult;
234
+ }
235
+ _getOverrideId(id, importer) {
236
+ var _a;
237
+ let overrideId;
238
+ for (let p of this._plugins) {
239
+ overrideId = (_a = p.transformId) === null || _a === void 0 ? void 0 : _a.call(p, id, importer);
240
+ if (overrideId) {
241
+ return overrideId;
242
+ }
243
+ }
244
+ if (id in this._virtualOverrides) {
245
+ overrideId = this._virtualOverrides[id];
246
+ }
247
+ else if (id in this._moduleOverrides) {
248
+ overrideId = this._moduleOverrides[id];
249
+ }
250
+ else if (!ps.isAbsolute(id) && importer) {
251
+ const absolutePath = this._resolveRelative(id, importer);
252
+ if (absolutePath && this._moduleOverrides[absolutePath] === importer) {
253
+ this._entriesForPass2.add(absolutePath); // for next pass
254
+ return;
255
+ }
256
+ if (absolutePath && absolutePath in this._moduleOverrides) {
257
+ overrideId = this._moduleOverrides[absolutePath];
258
+ }
259
+ }
260
+ return overrideId;
261
+ }
262
+ _resolve(id, importer) {
263
+ var _a, _b;
264
+ for (let p of this._plugins) {
265
+ const resolvedId = (_a = p.resolve) === null || _a === void 0 ? void 0 : _a.call(p, id, importer);
266
+ if (resolvedId) {
267
+ return resolvedId;
268
+ }
269
+ }
270
+ if (!importer) {
271
+ return id; // entry
272
+ }
273
+ else if (id in this._virtualOverrides) {
274
+ return id; // virtual module does not have real fs path
275
+ }
276
+ else if (id in this._moduleOverrides) {
277
+ return this._moduleOverrides[id];
278
+ }
279
+ else if (this._nodeModules.includes(id)) {
280
+ return id; // node module only use bare specifier as module id
281
+ }
282
+ else if (ps.isAbsolute(id)) {
283
+ return id;
284
+ }
285
+ else {
286
+ const resolved = this._resolveRelative(id, importer);
287
+ if (resolved) {
288
+ return (_b = this._moduleOverrides[resolved]) !== null && _b !== void 0 ? _b : resolved;
289
+ }
290
+ }
291
+ }
292
+ _resolveRelative(id, importer) {
293
+ const file = (0, path_utils_1.normalizePath)(ps.join(ps.dirname(importer), id));
294
+ if (ps.extname(file) && fs.existsSync(file)) {
295
+ return file;
296
+ }
297
+ // resolve extension less
298
+ for (const ext of this._resolveExtension) {
299
+ const fileExt = file + ext;
300
+ const indexExt = (0, path_utils_1.normalizePath)(ps.join(file, 'index')) + ext;
301
+ if (fs.existsSync(fileExt)) {
302
+ return fileExt;
303
+ }
304
+ else if (fs.existsSync(indexExt)) {
305
+ return indexExt;
306
+ }
307
+ }
308
+ }
309
+ _load(id) {
310
+ var _a;
311
+ for (let p of this._plugins) {
312
+ const loadedCode = (_a = p.load) === null || _a === void 0 ? void 0 : _a.call(p, id);
313
+ if (loadedCode) {
314
+ return loadedCode;
315
+ }
316
+ }
317
+ if (fs.existsSync(id)) {
318
+ let code = fs.readFileSync(id, 'utf8');
319
+ if (id.endsWith('.json')) {
320
+ code = `export default ${code};`;
321
+ }
322
+ return code;
323
+ }
324
+ else if (this._virtualOverrides[id]) {
325
+ return this._virtual2code[id];
326
+ }
327
+ }
328
+ _transform(file, code) {
329
+ file = (0, path_utils_1.normalizePath)(file);
330
+ for (let ex of this._excludeTransform) {
331
+ if (ex.test(file)) {
332
+ return {
333
+ code,
334
+ depIdList: [],
335
+ };
336
+ }
337
+ }
338
+ const depIdList = [];
339
+ if (ps.extname(file) === '.js') {
340
+ const dtsFile = (0, path_utils_1.toExtensionLess)(file) + '.d.ts';
341
+ if (fs.existsSync(dtsFile)) {
342
+ depIdList.push(dtsFile); // emit the .d.ts file
343
+ }
344
+ }
345
+ const importExportVisitor = (path) => {
346
+ // @ts-ignore
347
+ const source = path.node.source;
348
+ if (source) {
349
+ const specifier = source.value;
350
+ // add dependency
351
+ if (!this._nodeModules.includes(specifier)) {
352
+ // don't load node modules, we post install the modules in OH project
353
+ depIdList.push(specifier);
354
+ }
355
+ // transform import/export declaration if needed
356
+ const overrideId = this._getOverrideId(specifier, file);
357
+ if (overrideId) {
358
+ let relativePath = (0, path_utils_1.normalizePath)(ps.relative(ps.dirname(file), overrideId));
359
+ if (!relativePath.startsWith('.')) {
360
+ relativePath = './' + relativePath;
361
+ }
362
+ if (ps.extname(relativePath) === '.ts') {
363
+ relativePath = relativePath.slice(0, -3); // remove '.ts'
364
+ }
365
+ // traverse to transform specifier
366
+ (0, traverse_1.default)(path.node, {
367
+ StringLiteral(path) {
368
+ path.replaceWith(babel.types.stringLiteral(relativePath));
369
+ path.skip();
370
+ },
371
+ }, path.scope);
372
+ }
373
+ }
374
+ const importExportSpecifier = (path) => {
375
+ const name = path.node.local.name;
376
+ const alias = this._renameMap[name];
377
+ if (alias) {
378
+ path.replaceWith(babel.types.exportSpecifier(babel.types.identifier(alias), babel.types.identifier(alias)));
379
+ }
380
+ };
381
+ path.traverse({
382
+ ExportSpecifier: importExportSpecifier,
383
+ ImportSpecifier: importExportSpecifier,
384
+ });
385
+ };
386
+ const self = this;
387
+ const transformResult = babel.transformSync(code, {
388
+ configFile: false,
389
+ plugins: [
390
+ [plugin_syntax_typescript_1.default],
391
+ [plugin_syntax_decorators_1.default, {
392
+ version: '2018-09',
393
+ decoratorsBeforeExport: true,
394
+ }],
395
+ [
396
+ () => {
397
+ return {
398
+ name: 'custom-transform',
399
+ pre(file) {
400
+ const pluginPass = this;
401
+ (0, traverse_1.default)(file.ast, {
402
+ ClassProperty(path) {
403
+ const decoratorsPath = path.get('decorators');
404
+ if (Array.isArray(decoratorsPath)) {
405
+ const propertyValuePath = path.get('value');
406
+ const helperIdentifier = self._filedDecoratorHelper.addHelper(pluginPass.file);
407
+ decoratorsPath.forEach(decPath => {
408
+ const expPath = decPath.get('expression');
409
+ const type = expPath.node.type;
410
+ if (type === 'CallExpression') {
411
+ const decName = expPath.node.callee.name;
412
+ const args = expPath.node.arguments;
413
+ decPath.replaceWith(t.decorator(t.callExpression(helperIdentifier, [
414
+ t.identifier(decName),
415
+ (propertyValuePath.node ?
416
+ t.arrowFunctionExpression([], propertyValuePath.node) :
417
+ t.nullLiteral()),
418
+ ...args
419
+ ])));
420
+ }
421
+ else if (type === 'Identifier') {
422
+ const decName = expPath.node.name;
423
+ decPath.replaceWith(t.decorator(t.callExpression(helperIdentifier, [
424
+ t.identifier(decName),
425
+ (propertyValuePath.node ?
426
+ t.arrowFunctionExpression([], propertyValuePath.node) :
427
+ t.nullLiteral())
428
+ ])));
429
+ }
430
+ });
431
+ }
432
+ },
433
+ });
434
+ },
435
+ visitor: {
436
+ ImportDeclaration: importExportVisitor,
437
+ ExportDeclaration: importExportVisitor,
438
+ // TODO: here we rename class Rect and Path
439
+ CallExpression(path) {
440
+ if (path.node.callee.type === 'MemberExpression') {
441
+ const memberExpressionPath = path.get('callee');
442
+ const objectPath = memberExpressionPath.get('object');
443
+ const name = objectPath.node.name;
444
+ const alias = self._renameMap[name];
445
+ if (typeof alias === 'string' && path.node.callee.object.type === 'Identifier') {
446
+ objectPath.replaceWith(t.identifier(alias));
447
+ }
448
+ // TODO: for now, OH doesn't support standard console interface,
449
+ // so we need to ignore the type checking for console call expressions.
450
+ else if (name === 'console') {
451
+ path.node.leadingComments = [{
452
+ type: 'CommentLine',
453
+ value: ' @ts-ignore',
454
+ }];
455
+ }
456
+ }
457
+ else if (path.node.callee.type === 'Import') {
458
+ // TODO: for now, we transform `import('./xxx/xxx.js')` into `window.__cc_module_context__.import('./xxx/xxx.js')`
459
+ // we need to support import(`project://xxx`) in the future.
460
+ path.replaceWith(t.callExpression(t.memberExpression(t.memberExpression(t.identifier('window'), t.identifier('__cc_module_context__')), t.identifier('import')), path.node.arguments));
461
+ }
462
+ },
463
+ ClassDeclaration(path) {
464
+ const idPath = path.get('id');
465
+ const name = idPath.node.name;
466
+ const alias = self._renameMap[name];
467
+ if (typeof alias === 'string') {
468
+ idPath.replaceWith(t.identifier(alias));
469
+ }
470
+ },
471
+ NewExpression(path) {
472
+ const calleePath = path.get('callee');
473
+ // @ts-ignore
474
+ const name = calleePath.node.name;
475
+ if (name) {
476
+ const alias = self._renameMap[name];
477
+ if (typeof alias === 'string') {
478
+ calleePath.replaceWith(t.identifier(alias));
479
+ }
480
+ }
481
+ },
482
+ TSTypeAnnotation(path) {
483
+ // @ts-ignore
484
+ const typeName = path.node.typeAnnotation.typeName;
485
+ const childPath = path.get('typeAnnotation');
486
+ if (typeName) {
487
+ const name = typeName.name;
488
+ const alias = self._renameMap[name];
489
+ if (typeof alias === 'string') {
490
+ path.replaceWith(t.tsTypeAnnotation({
491
+ type: 'TSExpressionWithTypeArguments',
492
+ expression: t.identifier(alias),
493
+ }));
494
+ }
495
+ }
496
+ else if (childPath.type === 'TSLiteralType') {
497
+ const literalPath = childPath.get('literal');
498
+ if (literalPath.type === 'TemplateLiteral') {
499
+ path.replaceWith(t.tsTypeAnnotation(t.tsStringKeyword()));
500
+ }
501
+ }
502
+ },
503
+ Identifier(path) {
504
+ const name = path.node.name;
505
+ const alias = self._renameMap[name];
506
+ if (typeof alias === 'string') {
507
+ if (path.parent.type === 'ObjectProperty' || path.parent.type === 'TSPropertySignature') {
508
+ if (path.parent.key !== path.node) {
509
+ path.replaceWith(t.identifier(alias));
510
+ }
511
+ }
512
+ else if (path.parent.type === 'MemberExpression' || path.parent.type === 'OptionalMemberExpression') {
513
+ if (path.parent.property !== path.node) {
514
+ path.replaceWith(t.identifier(alias));
515
+ }
516
+ }
517
+ else if (!(path.parent.type === 'ClassMethod' && (path.parent.kind === 'get' || path.parent.kind === 'set' || path.parent.key === path.node))
518
+ && path.parent.type !== 'ClassProperty') {
519
+ const newIdentifier = t.identifier(alias);
520
+ if (path.node.typeAnnotation) {
521
+ newIdentifier.typeAnnotation = path.node.typeAnnotation;
522
+ }
523
+ path.replaceWith(newIdentifier);
524
+ }
525
+ }
526
+ },
527
+ }
528
+ };
529
+ }
530
+ ]
531
+ ],
532
+ });
533
+ return {
534
+ code: transformResult === null || transformResult === void 0 ? void 0 : transformResult.code,
535
+ depIdList,
536
+ };
537
+ }
538
+ _lintImport(lintFiles, verbose = false) {
539
+ return __awaiter(this, void 0, void 0, function* () {
540
+ const eslint = new eslint_1.ESLint({ fix: true,
541
+ cwd: __dirname,
542
+ resolvePluginsRelativeTo: __dirname,
543
+ useEslintrc: false,
544
+ baseConfig: {
545
+ parser: "@typescript-eslint/parser",
546
+ plugins: ["@typescript-eslint", "unused-imports"],
547
+ rules: {
548
+ "@typescript-eslint/consistent-type-imports": "error",
549
+ "unused-imports/no-unused-imports": "error",
550
+ },
551
+ } });
552
+ const results = yield eslint.lintFiles(lintFiles);
553
+ yield eslint_1.ESLint.outputFixes(results);
554
+ if (verbose) {
555
+ const formatter = yield eslint.loadFormatter();
556
+ const resultText = formatter.format(results);
557
+ console.log(resultText);
558
+ }
559
+ });
560
+ }
561
+ _buildIndex() {
562
+ const { outDir, root } = this._options;
563
+ if (outDir) {
564
+ const indexFile = (0, path_utils_1.normalizePath)(ps.join(outDir, 'index.ts'));
565
+ const ccFile = (0, path_utils_1.normalizePath)(ps.join(outDir, 'cc.ts'));
566
+ const systemCCFile = (0, path_utils_1.normalizePath)(ps.join(outDir, 'system-cc.js'));
567
+ let indexContent = '';
568
+ this._entries.forEach(item => {
569
+ const relative = (0, path_utils_1.normalizePath)(ps.relative(root, (0, path_utils_1.toExtensionLess)(item)));
570
+ indexContent += `export * from './${relative}';\n`;
571
+ });
572
+ const ccContent = (0, dedent_1.default) `import * as cc from './index';
573
+ // @ts-ignore
574
+ window.cc_module = cc;`;
575
+ const systemCCContent = (0, dedent_1.default) `System.register([], function (exports, module) {
576
+ return {
577
+ execute: function () {
578
+ window.__cc_module_context__ = module;
579
+
580
+ exports(window.cc_module);
581
+ }
582
+ };
583
+ });
584
+ `;
585
+ fs.outputFileSync(indexFile, indexContent, 'utf8');
586
+ fs.outputFileSync(ccFile, ccContent, 'utf8');
587
+ fs.outputFileSync(systemCCFile, systemCCContent, 'utf8');
588
+ }
589
+ }
590
+ _copyTypes() {
591
+ return __awaiter(this, void 0, void 0, function* () {
592
+ const { root, outDir } = this._options;
593
+ if (!outDir) {
594
+ return;
595
+ }
596
+ const dtsFiles = glob_1.glob.sync((0, path_utils_1.normalizePath)(ps.join(root, './@types/**/*.d.ts')));
597
+ for (let file of dtsFiles) {
598
+ const code = fs.readFileSync(file, 'utf8');
599
+ const relativePath = ps.relative(root, file);
600
+ const targetPath = (0, path_utils_1.normalizePath)(ps.join(outDir, relativePath));
601
+ fs.outputFileSync(targetPath, code, 'utf8');
602
+ }
603
+ // copy lib.dom.d.ts
604
+ // we use 4.2 version of typescript
605
+ const originalDomDts = (0, path_utils_1.normalizePath)(ps.join(__dirname, '../../../static/lib.dom.d.ts'));
606
+ const targetDomDts = (0, path_utils_1.normalizePath)(ps.join(outDir, '@types/lib.dom.d.ts'));
607
+ const code = fs.readFileSync(originalDomDts, 'utf8');
608
+ fs.outputFileSync(targetDomDts, code, 'utf8');
609
+ });
610
+ }
611
+ _addNodeModulesDeps() {
612
+ const { outDir } = this._options;
613
+ if (!outDir) {
614
+ return;
615
+ }
616
+ const pkgFile = (0, path_utils_1.normalizePath)(ps.join(outDir, '..', // src
617
+ '..', // cocos
618
+ '..', // ets
619
+ '..', // main
620
+ '..', // src
621
+ '..', // entry
622
+ 'package.json'));
623
+ if (!fs.existsSync(pkgFile)) {
624
+ return;
625
+ }
626
+ const jsonObj = fs.readJSONSync(pkgFile);
627
+ console.log(jsonObj);
628
+ // TODO
629
+ }
630
+ }
631
+ exports.EngineBuilder = EngineBuilder;
632
632
  //# sourceMappingURL=engine-builder.js.map