babel-plugin-hylid-bridge 2.10.0 → 2.11.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/CHANGELOG.md CHANGED
@@ -3,6 +3,14 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ ## [2.11.0] (2023-03-01)
7
+
8
+ **Note:** Version bump only for package babel-plugin-hylid-bridge
9
+
10
+
11
+
12
+
13
+
6
14
  ## [2.10.0] (2023-02-22)
7
15
 
8
16
  **Note:** Version bump only for package babel-plugin-hylid-bridge
@@ -0,0 +1 @@
1
+ export default function getLibraryDir(): string;
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = getLibraryDir;
7
+ var _utils = require("./utils");
8
+ var libraryDir;
9
+ function getLibraryDir() {
10
+ if (!libraryDir) {
11
+ var cwd = process.cwd();
12
+ try {
13
+ libraryDir = process.env.HYLID_BRIDGE_PACKAGE_DIR || require.resolve('hylid-bridge/package.json', {
14
+ paths: [cwd]
15
+ }).replace('package.json', '');
16
+ (0, _utils.log)("Find the hylid-bridge package: ".concat(libraryDir));
17
+ } catch (e) {
18
+ (0, _utils.error)("Can not resolve the hylid-bridge package from the directory: ".concat(cwd, "."), e);
19
+ }
20
+ }
21
+ return libraryDir;
22
+ }
package/lib/index.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ import type babelCore from '@babel/core';
2
+ import { PluginPass } from '@babel/core';
3
+ interface IState extends PluginPass {
4
+ usedJSAPIList: 'all' | string[];
5
+ }
6
+ declare const _default: (core: typeof babelCore, opts?: Record<string, any>) => babelCore.PluginObj<IState>;
7
+ export default _default;
package/lib/index.js ADDED
@@ -0,0 +1,241 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ var _typeof = require("@babel/runtime/helpers/typeof");
5
+ Object.defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ exports.default = void 0;
9
+ var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
10
+ var _path = _interopRequireDefault(require("path"));
11
+ var _fsExtra = _interopRequireDefault(require("fs-extra"));
12
+ var _lodash = _interopRequireDefault(require("lodash"));
13
+ var babelTypes = _interopRequireWildcard(require("@babel/types"));
14
+ var _getLibraryDir = _interopRequireDefault(require("./getLibraryDir"));
15
+ var utils = _interopRequireWildcard(require("./utils"));
16
+ function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
17
+ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
18
+ /**
19
+ * https://astexplorer.net/
20
+ */
21
+
22
+ var identifierPrefix = '__hylid_bridge__';
23
+ var libraryName = 'hylid-bridge';
24
+ var libraryDir = (0, _getLibraryDir.default)();
25
+ function snakeCaseTarget(value) {
26
+ if (value === 'H5') {
27
+ return 'h5';
28
+ }
29
+ return _lodash.default.snakeCase(value);
30
+ }
31
+ function isTargetSupported(target) {
32
+ var libraryDir = (0, _getLibraryDir.default)();
33
+ return ['MpWeb', 'Mp', 'Web'].some(function (prefix) {
34
+ if (target.startsWith(prefix)) {
35
+ var targetClientDir = _path.default.resolve(libraryDir, 'lib/clients', snakeCaseTarget(prefix), snakeCaseTarget(target.replace(prefix, '')));
36
+ return _fsExtra.default.existsSync(targetClientDir);
37
+ }
38
+ return false;
39
+ });
40
+ }
41
+ function getTargets(customTargets) {
42
+ var targets = customTargets || (process.env.HYLID_BRIDGE_TARGETS ? process.env.HYLID_BRIDGE_TARGETS.split(',') : []);
43
+ return targets.filter(isTargetSupported);
44
+ }
45
+ function isApiExists(name, target) {
46
+ var targetSplit = splitTarget(target);
47
+ if (targetSplit.length !== 2) {
48
+ throw new Error("Wrong target configuration: ".concat(target, "."));
49
+ }
50
+ return _fsExtra.default.existsSync(_path.default.resolve(libraryDir, "./lib/clients/".concat(targetSplit[0], "/").concat(targetSplit[1], "/").concat(name, ".js")));
51
+ }
52
+ function getUserAppEnvPath(appEnvPath) {
53
+ var realAppEnvPath = appEnvPath !== null && appEnvPath !== void 0 ? appEnvPath : _path.default.resolve(process.cwd(), './src/appEnv.ts');
54
+ if (!_fsExtra.default.existsSync(realAppEnvPath)) {
55
+ utils.log("Can not find the appEnv module at the path: ".concat(realAppEnvPath, "."));
56
+ return;
57
+ }
58
+ return realAppEnvPath;
59
+ }
60
+ function splitTarget(target) {
61
+ var prefixList = ['MpWeb', 'Mp', 'Web'];
62
+ for (var i = 0, il = prefixList.length; i < il; i++) {
63
+ var prefix = prefixList[i];
64
+ if (target.startsWith(prefix)) {
65
+ return [snakeCaseTarget(prefix), snakeCaseTarget(target.replace(prefix, ''))];
66
+ }
67
+ }
68
+ throw new Error("Invalid bridge target: ".concat(target, "."));
69
+ }
70
+ var myLocalName = "".concat(identifierPrefix, "my__");
71
+ function getNames(node, scope, state, targets) {
72
+ var _state$filename;
73
+ if (node.object.type === 'Identifier' && node.property.type === 'Identifier' &&
74
+ // Remix 中会编译所有 node_modules 下的模块
75
+ !((_state$filename = state.filename) !== null && _state$filename !== void 0 && _state$filename.includes("".concat(_path.default.sep, "node_modules").concat(_path.default.sep, "hylid-bridge").concat(_path.default.sep))) && targets && targets.length && !scope.hasBinding('my')) {
76
+ return {
77
+ objectName: node.object.name,
78
+ propertyName: node.property.name
79
+ };
80
+ }
81
+ return {
82
+ objectName: undefined,
83
+ propertyName: undefined
84
+ };
85
+ }
86
+ function isJSAPIInTargets(jsapiName, targets, filename) {
87
+ return targets.every(function (target) {
88
+ var targetSplit = splitTarget(target);
89
+ if (!isApiExists(jsapiName, target)) {
90
+ utils.warn("Can not find the API `".concat(jsapiName, "` in `").concat(_path.default.resolve(libraryDir, './lib/clients/' + targetSplit[0] + '/' + targetSplit[1]), "`. Fallback to import all API codes of ").concat(target, ". Current file path: `").concat(filename, "`."));
91
+ return false;
92
+ }
93
+ return true;
94
+ });
95
+ }
96
+ var _default = function _default(core, opts) {
97
+ var targets = getTargets(opts === null || opts === void 0 ? void 0 : opts.targets);
98
+ var userAppEnvPath = getUserAppEnvPath(opts === null || opts === void 0 ? void 0 : opts.appEnvPath);
99
+ return {
100
+ name: 'babel-plugin-hylid-bridge',
101
+ visitor: {
102
+ MemberExpression: function MemberExpression(path, state) {
103
+ var _getNames = getNames(path.node, path.scope, state, targets),
104
+ objectName = _getNames.objectName,
105
+ propertyName = _getNames.propertyName;
106
+ if (!propertyName || propertyName === 'call' || objectName !== 'my') {
107
+ return;
108
+ }
109
+ var newNode = core.types.cloneNode(path.node, true, true);
110
+ newNode.object = core.types.identifier(myLocalName);
111
+ if (state.usedJSAPIList === 'all') {
112
+ path.replaceWith(newNode);
113
+ return;
114
+ }
115
+ if (path.node.computed) {
116
+ state.usedJSAPIList = 'all';
117
+ utils.warn("Detect visiting the property of `my` with computed mode: my[".concat(propertyName, "]. Fallback to import all API codes of ").concat(targets.join(','), ". Current file path: `").concat(state.filename, "`."));
118
+ } else {
119
+ state.usedJSAPIList = state.usedJSAPIList || [];
120
+ var name = propertyName;
121
+ if (isJSAPIInTargets(name, targets, state.filename)) {
122
+ state.usedJSAPIList.push(name);
123
+ } else {
124
+ state.usedJSAPIList = 'all';
125
+ }
126
+ }
127
+ path.replaceWith(newNode);
128
+ },
129
+ CallExpression: function CallExpression(path, state) {
130
+ if (path.node.callee.type !== 'MemberExpression') {
131
+ return;
132
+ }
133
+ var _getNames2 = getNames(path.node.callee, path.scope, state, targets),
134
+ objectName = _getNames2.objectName,
135
+ propertyName = _getNames2.propertyName;
136
+ if (objectName !== 'my' || propertyName !== 'call' || !path.node.arguments[0] || path.node.arguments[0].type !== 'StringLiteral') {
137
+ return;
138
+ }
139
+ var newNode = core.types.callExpression(babelTypes.memberExpression(babelTypes.identifier(myLocalName), babelTypes.identifier(path.node.arguments[0].value)), path.node.arguments.slice(1));
140
+ if (state.usedJSAPIList === 'all') {
141
+ path.replaceWith(newNode);
142
+ return;
143
+ }
144
+ state.usedJSAPIList = state.usedJSAPIList || [];
145
+ var name = path.node.arguments[0].value;
146
+ if (isJSAPIInTargets(name, targets, state.filename)) {
147
+ state.usedJSAPIList.push(name);
148
+ } else {
149
+ state.usedJSAPIList = 'all';
150
+ }
151
+ path.replaceWith(newNode);
152
+ },
153
+ Program: {
154
+ exit: function exit(path, state) {
155
+ if (!state.usedJSAPIList) {
156
+ return;
157
+ }
158
+ var usedJSAPIList = state.usedJSAPIList || [];
159
+ var appEnvLocalName = "".concat(identifierPrefix, "appEnv__");
160
+ if (path.scope.hasBinding(appEnvLocalName)) {
161
+ return;
162
+ }
163
+ var innerAppEnvLocalName = "".concat(identifierPrefix, "innerAppEnv__");
164
+ var userAppEnvLocalName = "".concat(identifierPrefix, "userAppEnv__");
165
+ var nodes = [babelTypes.importDeclaration([babelTypes.importDefaultSpecifier(babelTypes.identifier(innerAppEnvLocalName))], babelTypes.stringLiteral("".concat(libraryName, "/lib/appEnv")))];
166
+ if (userAppEnvPath) {
167
+ var relativePath = _path.default.relative(_path.default.dirname(state.filename), userAppEnvPath.replace(/\.ts$/, ''));
168
+ nodes.push(babelTypes.importDeclaration([babelTypes.importDefaultSpecifier(babelTypes.identifier(userAppEnvLocalName))], babelTypes.stringLiteral(relativePath.startsWith('../') ? relativePath : "./".concat(relativePath))));
169
+ } else {
170
+ nodes.push(babelTypes.variableDeclaration('var', [babelTypes.variableDeclarator(babelTypes.identifier(userAppEnvLocalName), babelTypes.objectExpression([]))]));
171
+ }
172
+ var objectSpreadName = "".concat(identifierPrefix, "objectSpread__");
173
+ nodes.push(babelTypes.importDeclaration([babelTypes.importDefaultSpecifier(babelTypes.identifier(objectSpreadName))], babelTypes.stringLiteral("".concat(libraryName, "/lib/objectSpread"))), babelTypes.variableDeclaration('var', [babelTypes.variableDeclarator(babelTypes.identifier(appEnvLocalName), babelTypes.callExpression(babelTypes.identifier(objectSpreadName), [babelTypes.identifier(innerAppEnvLocalName), babelTypes.identifier(userAppEnvLocalName)]))]));
174
+ if (usedJSAPIList === 'all') {
175
+ nodes.push.apply(nodes, (0, _toConsumableArray2.default)(targets.map(function (target) {
176
+ var targetSplit = splitTarget(target);
177
+ return babelTypes.importDeclaration([babelTypes.importDefaultSpecifier(babelTypes.identifier("".concat(identifierPrefix).concat(targetSplit[0], "_").concat(targetSplit[1], "_my__")))], babelTypes.stringLiteral("".concat(libraryName, "/lib/clients/").concat(targetSplit[0], "/").concat(targetSplit[1], "/index")));
178
+ })));
179
+ var buildElseIf = function buildElseIf(targetList) {
180
+ if (!targetList.length) {
181
+ return;
182
+ }
183
+ var target = targetList[0];
184
+ var targetSplit = splitTarget(target);
185
+ return babelTypes.ifStatement(babelTypes.identifier("".concat(appEnvLocalName, ".").concat(_lodash.default.camelCase("is_".concat(targetSplit[0], "_").concat(targetSplit[1])))), babelTypes.blockStatement([babelTypes.expressionStatement(babelTypes.assignmentExpression('=', babelTypes.identifier(myLocalName), babelTypes.identifier("".concat(identifierPrefix).concat(targetSplit[0], "_").concat(targetSplit[1], "_my__"))))]), buildElseIf(targetList.slice(1)));
186
+ };
187
+ nodes.push(babelTypes.variableDeclaration('var', [babelTypes.variableDeclarator(babelTypes.identifier(myLocalName))]));
188
+ // Do not generate the `if statement` when there is just one target.
189
+ if (targets.length === 1) {
190
+ var targetSplit = splitTarget(targets[0]);
191
+ nodes.push(babelTypes.expressionStatement(babelTypes.assignmentExpression('=', babelTypes.identifier(myLocalName), babelTypes.identifier("".concat(identifierPrefix).concat(targetSplit[0], "_").concat(targetSplit[1], "_my__")))));
192
+ } else {
193
+ var elseIfNode = buildElseIf(targets);
194
+ elseIfNode && nodes.push(elseIfNode);
195
+ }
196
+ } else if (usedJSAPIList.length) {
197
+ var normalizedJSAPIList = _lodash.default.uniq(usedJSAPIList);
198
+ normalizedJSAPIList.forEach(function (name) {
199
+ targets.forEach(function (target) {
200
+ var targetSplit = splitTarget(target);
201
+ var localName = "".concat(identifierPrefix).concat(targetSplit[0], "_").concat(targetSplit[1], "_").concat(name, "__");
202
+ var n = babelTypes.importDeclaration([babelTypes.importDefaultSpecifier(babelTypes.identifier(localName))], babelTypes.stringLiteral("".concat(libraryName, "/lib/clients/").concat(targetSplit[0], "/").concat(targetSplit[1], "/").concat(name)));
203
+ nodes.push(n);
204
+ });
205
+ });
206
+ var _buildElseIf = function _buildElseIf(targetList) {
207
+ if (!targetList.length) {
208
+ return;
209
+ }
210
+ var target = targetList[0];
211
+ var targetSplit = splitTarget(target);
212
+ var propertyList = normalizedJSAPIList.map(function (name) {
213
+ return babelTypes.objectProperty(babelTypes.identifier(name), babelTypes.identifier("".concat(identifierPrefix).concat(targetSplit[0], "_").concat(targetSplit[1], "_").concat(name, "__")));
214
+ });
215
+ return babelTypes.ifStatement(babelTypes.identifier("".concat(appEnvLocalName, ".").concat(_lodash.default.camelCase("is_".concat(targetSplit[0], "_").concat(targetSplit[1])))), babelTypes.blockStatement([babelTypes.expressionStatement(babelTypes.assignmentExpression('=', babelTypes.identifier(myLocalName), babelTypes.objectExpression(propertyList)))]), _buildElseIf(targetList.slice(1)));
216
+ };
217
+ nodes.push(babelTypes.variableDeclaration('var', [babelTypes.variableDeclarator(babelTypes.identifier(myLocalName))]));
218
+ // Do not generate the `if statement` when there is just one target.
219
+ if (targets.length === 1) {
220
+ var _targetSplit = splitTarget(targets[0]);
221
+ var propertyList = normalizedJSAPIList.map(function (name) {
222
+ return babelTypes.objectProperty(babelTypes.identifier(name), babelTypes.identifier("".concat(identifierPrefix).concat(_targetSplit[0], "_").concat(_targetSplit[1], "_").concat(name, "__")));
223
+ });
224
+ nodes.push(babelTypes.expressionStatement(babelTypes.assignmentExpression('=', babelTypes.identifier(myLocalName), babelTypes.objectExpression(propertyList))));
225
+ } else {
226
+ var _elseIfNode = _buildElseIf(targets);
227
+ _elseIfNode && nodes.push(_elseIfNode);
228
+ }
229
+ }
230
+ if (nodes.length) {
231
+ path.unshiftContainer('body', nodes);
232
+ }
233
+ if (targets.length && (usedJSAPIList === 'all' || usedJSAPIList.length)) {
234
+ utils.log("Successfully inject the Hylid-bridge into ".concat(state.filename, " to support the targets: ").concat(targets.join(','), "."));
235
+ }
236
+ }
237
+ }
238
+ }
239
+ };
240
+ };
241
+ exports.default = _default;
package/lib/utils.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export declare function log(...args: Parameters<typeof console.log>): void;
2
+ export declare function error(...args: Parameters<typeof console.error>): void;
3
+ export declare function warn(...args: Parameters<typeof console.error>): void;
package/lib/utils.js ADDED
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.error = error;
8
+ exports.log = log;
9
+ exports.warn = warn;
10
+ var _chalk = _interopRequireDefault(require("chalk"));
11
+ function log() {
12
+ var _console;
13
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
14
+ args[_key] = arguments[_key];
15
+ }
16
+ (_console = console).log.apply(_console, [_chalk.default.bold.green('[LOG]')].concat(args));
17
+ }
18
+ function error() {
19
+ var _console2;
20
+ for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
21
+ args[_key2] = arguments[_key2];
22
+ }
23
+ (_console2 = console).error.apply(_console2, [_chalk.default.bold.red('[ERROR]')].concat(args));
24
+ }
25
+ function warn() {
26
+ var _console3;
27
+ for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
28
+ args[_key3] = arguments[_key3];
29
+ }
30
+ (_console3 = console).error.apply(_console3, [_chalk.default.bold.yellow('[WARN]')].concat(args));
31
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "babel-plugin-hylid-bridge",
3
- "version": "2.10.0",
3
+ "version": "2.11.1",
4
4
  "description": "babel-plugin-hylid-bridge",
5
5
  "main": "lib/index.js",
6
6
  "files": [