@cocos/ccbuild 1.1.14 → 2.0.0-alpha.0

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