babel-plugin-hylid-bridge 0.0.1 → 0.0.2-dev.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.
@@ -0,0 +1 @@
1
+ export default function combieExports(index1Path: string, index2Path: string): string;
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.default = combieExports;
8
+ var _path = _interopRequireDefault(require("path"));
9
+ var _fsExtra = _interopRequireDefault(require("fs-extra"));
10
+ var _hashIt = _interopRequireDefault(require("hash-it"));
11
+ var isTest = process.env.NODE_ENV === 'test';
12
+ function combieExports(index1Path, index2Path) {
13
+ var indexPath = _path.default.resolve(__dirname, '..', '.temp', (isTest ? 'test' : (0, _hashIt.default)("".concat(index1Path).concat(index2Path))) + '.js');
14
+ _fsExtra.default.ensureFileSync(indexPath);
15
+ _fsExtra.default.writeFileSync(indexPath, "\n import index1 from '".concat(index1Path, "';\n import index2 from '").concat(index2Path, "';\n\n export default {\n ...index1,\n ...index2,\n };\n "));
16
+ return indexPath;
17
+ }
@@ -0,0 +1,2 @@
1
+ export default function (targets: string[], libraryDir: string): void;
2
+ export declare function filterWhichCanIUseJsapi(apiList: string[]): void;
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.default = _default;
8
+ exports.filterWhichCanIUseJsapi = filterWhichCanIUseJsapi;
9
+ var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
10
+ var _path = _interopRequireDefault(require("path"));
11
+ var _fsExtra = _interopRequireDefault(require("fs-extra"));
12
+ var _getLibraryDir = _interopRequireDefault(require("./getLibraryDir"));
13
+ // 筛选 hylid-bridge 兼容度信息
14
+ function _default(targets, libraryDir) {
15
+ var lib = libraryDir || (0, _getLibraryDir.default)();
16
+ // 获取 lib 下的 bridge.js 文件
17
+ var bridgeFile = _path.default.join(lib, 'lib', 'whichCanIUse', 'compatibilities.json');
18
+ var compatibilities = JSON.parse(_fsExtra.default.readFileSync(bridgeFile, 'utf-8'));
19
+ var envMaps = compatibilities.envMaps;
20
+ var envs = [];
21
+ var targetsList = targets.map(function (target) {
22
+ var res = {
23
+ platform: '',
24
+ clientName: ''
25
+ };
26
+ ['Mp', 'MpWeb', 'Web'].some(function (prefix) {
27
+ if (target.startsWith(prefix)) {
28
+ res.platform = prefix.toUpperCase();
29
+ res.clientName = target.replace(prefix, '').toUpperCase();
30
+ }
31
+ });
32
+ return res;
33
+ });
34
+ envMaps.forEach(function (env, index) {
35
+ var _env$split = env.split('_'),
36
+ _env$split2 = (0, _slicedToArray2.default)(_env$split, 3),
37
+ clientName = _env$split2[0],
38
+ _ = _env$split2[1],
39
+ platform = _env$split2[2];
40
+ if (targetsList.some(function (item) {
41
+ return item.platform === platform && item.clientName === clientName;
42
+ })) {
43
+ envs.push(index);
44
+ }
45
+ });
46
+ compatibilities.data.forEach(function (item) {
47
+ item.compatibilities = item.compatibilities.filter(function (i) {
48
+ return envs.includes(i.env);
49
+ });
50
+ });
51
+ compatibilities.data = compatibilities.data.filter(function (item) {
52
+ return item.compatibilities.length > 0;
53
+ });
54
+ _fsExtra.default.writeFileSync(bridgeFile, JSON.stringify(compatibilities));
55
+ }
56
+ // 从 api 维度筛除数据
57
+ function filterWhichCanIUseJsapi(apiList) {
58
+ var lib = (0, _getLibraryDir.default)();
59
+ var bridgeFile = _path.default.join(lib, 'lib', 'whichCanIUse', 'compatibilities.json');
60
+ var compatibilities = JSON.parse(_fsExtra.default.readFileSync(bridgeFile, 'utf-8'));
61
+ compatibilities.data = compatibilities.data.filter(function (item) {
62
+ return apiList.includes(item.apiName);
63
+ });
64
+ _fsExtra.default.writeFileSync(bridgeFile, JSON.stringify(compatibilities));
65
+ }
@@ -0,0 +1 @@
1
+ export default function generateJSAPIs(targets: string[], libraryDir: string): void;
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.default = generateJSAPIs;
8
+ var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
9
+ var _path = _interopRequireDefault(require("path"));
10
+ var _fsExtra = _interopRequireDefault(require("fs-extra"));
11
+ var _parser = require("@babel/parser");
12
+ var _traverse = _interopRequireDefault(require("@babel/traverse"));
13
+ var _generator = _interopRequireDefault(require("@babel/generator"));
14
+ var _getLibraryDir = _interopRequireDefault(require("./getLibraryDir"));
15
+ var _helper = require("./helper");
16
+ function generateJSAPIs(targets, libraryDir) {
17
+ var lib = libraryDir || (0, _getLibraryDir.default)();
18
+ // 获取当前配置的环境信息
19
+ var appEnvList = targets.reduce(function (acc, target) {
20
+ var _splitTarget = (0, _helper.splitTarget)(target),
21
+ _splitTarget2 = (0, _slicedToArray2.default)(_splitTarget, 2),
22
+ platform = _splitTarget2[0],
23
+ client = _splitTarget2[1];
24
+ acc.push("".concat((0, _helper.camelCase)("is_".concat(platform, "_").concat(client))));
25
+ return acc;
26
+ }, []);
27
+ // 获取 lib 下的 bridge.js 文件
28
+ var bridgeFile = _path.default.join(lib, 'lib', 'bridges.js');
29
+ var ast = (0, _parser.parse)(_fsExtra.default.readFileSync(bridgeFile, 'utf-8'), {
30
+ sourceType: 'module'
31
+ });
32
+ (0, _traverse.default)(ast, {
33
+ IfStatement: function IfStatement(path) {
34
+ /**
35
+ * if 条件里有 n 多种写法,test 对应 n 多中类型。
36
+ * 下面为了方便,直接尝试访问 object.name 是否是 appEnv,在 bridge.js 中,符合这个条件的,一定是 jsapi 函数中 if 判断条件
37
+ */
38
+ var _ref = path.node.test || {},
39
+ object = _ref.object,
40
+ property = _ref.property;
41
+ if ((object === null || object === void 0 ? void 0 : object.name) === 'appEnv') {
42
+ var env = property.name;
43
+ // 删除不是目标的 appEnv 判断代码
44
+ if (!appEnvList.includes(env)) {
45
+ path.remove();
46
+ }
47
+ }
48
+ }
49
+ });
50
+ // 生成文件
51
+ var outInnerPath = _path.default.join(lib, 'lib', 'babel-compact-inner.js');
52
+ var outExportPath = _path.default.join(lib, 'lib', 'babel-compact.js');
53
+ var codes = ['// auto generated', "export * from './index'", (0, _generator.default)(ast).code];
54
+ var exportCodes = ['// auto generated', "export * from './babel-compact-inner'", "export * as default from './babel-compact-inner'"];
55
+ _fsExtra.default.writeFileSync(outExportPath, exportCodes.join('\n'));
56
+ _fsExtra.default.writeFileSync(outInnerPath, codes.join('\n'));
57
+ }
@@ -4,24 +4,30 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.default = getLibraryDir;
7
-
8
7
  var _utils = require("./utils");
9
-
10
8
  var libraryDir;
11
-
12
9
  function getLibraryDir() {
13
10
  if (!libraryDir) {
14
11
  var cwd = process.cwd();
15
-
16
12
  try {
17
- libraryDir = process.env.HYLID_BRIDGE_PACKAGE_DIR || require.resolve('hylid-bridge/package.json', {
13
+ // 找到依赖的 hylid-bridge,内外网版本同时找
14
+ var pathInternal = require.resolve('@alipay/hylid-bridge/package.json', {
18
15
  paths: [cwd]
19
16
  }).replace('package.json', '');
17
+ var path = require.resolve('hylid-bridge/package.json', {
18
+ paths: [cwd]
19
+ }).replace('package.json', '');
20
+ // 本地开发时,只安装了内网版本的包,外网的的包会找到 packages 目录下的开发包,需要忽略该情况
21
+ if (!pathInternal.includes('hylid-bridge/packages')) {
22
+ libraryDir = pathInternal;
23
+ }
24
+ if (!path.includes('hylid-bridge/packages')) {
25
+ libraryDir = path;
26
+ }
27
+ (0, _utils.log)("Find the hylid-bridge package: ".concat(libraryDir));
20
28
  } catch (e) {
21
29
  (0, _utils.error)("Can not resolve the hylid-bridge package from the directory: ".concat(cwd, "."), e);
22
30
  }
23
31
  }
24
-
25
- (0, _utils.log)("Find the hylid-bridge package: ".concat(libraryDir));
26
32
  return libraryDir;
27
33
  }
@@ -0,0 +1,25 @@
1
+ import type babelCore from '@babel/core';
2
+ import { PluginPass } from '@babel/core';
3
+ export declare function snakeCaseTarget(input: string): string;
4
+ export declare function isTargetSupported(target: string, libraryDir: string): boolean;
5
+ export declare function getTargets(libraryDir: string, customTargets?: string[]): string[];
6
+ export declare function isApiExists(name: string, target: string, libraryDir: string, polyfillDir?: string): boolean | "" | undefined;
7
+ export declare function getUserAppEnvPath(appEnvPath?: string): string | undefined;
8
+ export declare function splitTarget(target: string): string[];
9
+ interface IState extends PluginPass {
10
+ usedJSAPIList: 'all' | string[];
11
+ }
12
+ export declare function getNames(node: babelCore.NodePath<babelCore.types.MemberExpression>['node'], scope: babelCore.NodePath<babelCore.types.MemberExpression>['scope'], state: IState, targets: string[]): {
13
+ objectName: string;
14
+ propertyName: undefined;
15
+ } | {
16
+ objectName: string;
17
+ propertyName: string;
18
+ } | {
19
+ objectName: undefined;
20
+ propertyName: undefined;
21
+ };
22
+ export declare function isJSAPIInTargets(jsapiName: string, targets: string[], filename: string, libraryDir: string, polyfillDir?: string): boolean;
23
+ export declare function camelCase(input: string): string;
24
+ export declare function compareVersion(version1: string, version2: string): number;
25
+ export {};
package/lib/helper.js ADDED
@@ -0,0 +1,140 @@
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.camelCase = camelCase;
9
+ exports.compareVersion = compareVersion;
10
+ exports.getNames = getNames;
11
+ exports.getTargets = getTargets;
12
+ exports.getUserAppEnvPath = getUserAppEnvPath;
13
+ exports.isApiExists = isApiExists;
14
+ exports.isJSAPIInTargets = isJSAPIInTargets;
15
+ exports.isTargetSupported = isTargetSupported;
16
+ exports.snakeCaseTarget = snakeCaseTarget;
17
+ exports.splitTarget = splitTarget;
18
+ var _path = _interopRequireDefault(require("path"));
19
+ var _fsExtra = _interopRequireDefault(require("fs-extra"));
20
+ var utils = _interopRequireWildcard(require("./utils"));
21
+ function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
22
+ function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
23
+ function snakeCaseTarget(input) {
24
+ var words = input.replace(/[^a-zA-Z0-9]+/g, ' ').trim();
25
+ var wordArray = words.split(' ');
26
+ var snakeCasedWords = wordArray.map(function (word) {
27
+ return word.replace(/[A-Z]/g, function (match, index) {
28
+ return index === 0 ? match.toLowerCase() : "_".concat(match.toLowerCase());
29
+ });
30
+ });
31
+ return snakeCasedWords.join('_');
32
+ }
33
+ function isTargetSupported(target, libraryDir) {
34
+ return ['MpWeb', 'Mp', 'Web'].some(function (prefix) {
35
+ if (target.startsWith(prefix)) {
36
+ var targetClientDir = _path.default.resolve(libraryDir, 'lib/clients', snakeCaseTarget(prefix), snakeCaseTarget(target.replace(prefix, '')));
37
+ return _fsExtra.default.existsSync(targetClientDir);
38
+ }
39
+ return false;
40
+ });
41
+ }
42
+ function getTargets(libraryDir, customTargets) {
43
+ var targets = customTargets || (process.env.HYLID_BRIDGE_TARGETS ? process.env.HYLID_BRIDGE_TARGETS.split(',') : []);
44
+ return targets.filter(function (target) {
45
+ return isTargetSupported(target, libraryDir);
46
+ });
47
+ }
48
+ function isApiExists(name, target, libraryDir, polyfillDir) {
49
+ var targetSplit = splitTarget(target);
50
+ if (targetSplit.length !== 2) {
51
+ throw new Error("Wrong target configuration: ".concat(target, "."));
52
+ }
53
+ return _fsExtra.default.existsSync(_path.default.resolve(libraryDir, "./lib/clients/".concat(targetSplit[0], "/").concat(targetSplit[1], "/").concat(name, ".js"))) || polyfillDir && (_fsExtra.default.existsSync(_path.default.resolve(polyfillDir, "./".concat(targetSplit[0], "/").concat(targetSplit[1], "/").concat(name, ".js"))) || _fsExtra.default.existsSync(_path.default.resolve(polyfillDir, "./".concat(targetSplit[0], "/").concat(targetSplit[1], "/").concat(name, ".ts"))));
54
+ }
55
+ function getUserAppEnvPath(appEnvPath) {
56
+ var realAppEnvPath = appEnvPath !== null && appEnvPath !== void 0 ? appEnvPath : _path.default.resolve(process.cwd(), './src/appEnv.ts');
57
+ if (!_fsExtra.default.existsSync(realAppEnvPath)) {
58
+ utils.log("Can not find the appEnv module at the path: ".concat(realAppEnvPath, "."));
59
+ return;
60
+ }
61
+ return realAppEnvPath;
62
+ }
63
+ function splitTarget(target) {
64
+ var prefixList = ['MpWeb', 'Mp', 'Web'];
65
+ for (var i = 0, il = prefixList.length; i < il; i++) {
66
+ var prefix = prefixList[i];
67
+ if (target.startsWith(prefix)) {
68
+ return [snakeCaseTarget(prefix), snakeCaseTarget(target.replace(prefix, ''))];
69
+ }
70
+ }
71
+ throw new Error("Invalid bridge target: ".concat(target, "."));
72
+ }
73
+ function getNames(node, scope, state, targets) {
74
+ var _state$filename;
75
+ // my.alert || my[a]
76
+ if (node.object.type === 'Identifier' && node.property.type === 'Identifier' &&
77
+ // Remix 中会编译所有 node_modules 下的模块
78
+ !((_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')) {
79
+ return node.computed ? {
80
+ objectName: node.object.name,
81
+ propertyName: undefined
82
+ } : {
83
+ objectName: node.object.name,
84
+ propertyName: node.property.name
85
+ };
86
+ }
87
+ // my['alert']
88
+ if (node.object.type === 'Identifier' && node.property.type === 'StringLiteral' && node.computed && targets && targets.length && !scope.hasBinding('my')) {
89
+ return {
90
+ objectName: node.object.name,
91
+ propertyName: node.property.value
92
+ };
93
+ }
94
+ return {
95
+ objectName: undefined,
96
+ propertyName: undefined
97
+ };
98
+ }
99
+ function isJSAPIInTargets(jsapiName, targets, filename, libraryDir, polyfillDir) {
100
+ return targets.every(function (target) {
101
+ var targetSplit = splitTarget(target);
102
+ if (!isApiExists(jsapiName, target, libraryDir, polyfillDir)) {
103
+ 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, "`."));
104
+ return false;
105
+ }
106
+ return true;
107
+ });
108
+ }
109
+ // lodash 把数字后面第一个字符变大了,所以这里单独实现下
110
+ function camelCase(input) {
111
+ var words = input.replace(/[^a-zA-Z0-9]+/g, ' ').trim();
112
+ var wordArray = words.split(' ');
113
+ var camelCasedWords = wordArray.map(function (word, index) {
114
+ if (index === 0) {
115
+ return word.toLowerCase();
116
+ }
117
+ return word.charAt(0).toUpperCase() + word.slice(1);
118
+ });
119
+ return camelCasedWords.join('');
120
+ }
121
+ // 用于 babel 插件中比较 hylid-bridge 版本号
122
+ function compareVersion(version1, version2) {
123
+ // 删除 alpha 后缀进行比较,4.0.0-alpha.1 => 4.0.0
124
+ version1 = version1.split('-')[0];
125
+ version2 = version2.split('-')[0];
126
+ var v1Parts = version1.split('.').map(Number);
127
+ var v2Parts = version2.split('.').map(Number);
128
+ var maxLength = Math.max(v1Parts.length, v2Parts.length);
129
+ for (var i = 0; i < maxLength; i++) {
130
+ var v1 = v1Parts[i] || 0;
131
+ var v2 = v2Parts[i] || 0;
132
+ if (v1 > v2) {
133
+ return 1;
134
+ }
135
+ if (v1 < v2) {
136
+ return -1;
137
+ }
138
+ }
139
+ return 0;
140
+ }
package/lib/index.d.ts CHANGED
@@ -2,6 +2,14 @@ import type babelCore from '@babel/core';
2
2
  import { PluginPass } from '@babel/core';
3
3
  interface IState extends PluginPass {
4
4
  usedJSAPIList: 'all' | string[];
5
+ whichCanIUseJsapiList: string[];
5
6
  }
6
- declare const _default: (_: typeof babelCore, opts?: Record<string, any> | undefined) => babelCore.PluginObj<IState>;
7
+ declare const _default: (core: typeof babelCore, opts?: {
8
+ targets?: string[];
9
+ appEnvPath?: string;
10
+ libraryDir?: string;
11
+ polyfillDir?: string;
12
+ transformMy?: boolean;
13
+ compact?: boolean;
14
+ }) => babelCore.PluginObj<IState>;
7
15
  export default _default;
package/lib/index.js CHANGED
@@ -1,184 +1,221 @@
1
1
  "use strict";
2
2
 
3
3
  var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
-
5
4
  var _typeof = require("@babel/runtime/helpers/typeof");
6
-
7
5
  Object.defineProperty(exports, "__esModule", {
8
6
  value: true
9
7
  });
10
8
  exports.default = void 0;
11
-
12
9
  var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
13
-
14
10
  var _path = _interopRequireDefault(require("path"));
15
-
16
11
  var _fsExtra = _interopRequireDefault(require("fs-extra"));
17
-
18
12
  var _lodash = _interopRequireDefault(require("lodash"));
19
-
20
13
  var babelTypes = _interopRequireWildcard(require("@babel/types"));
21
-
22
14
  var _getLibraryDir = _interopRequireDefault(require("./getLibraryDir"));
23
-
24
- var utils = _interopRequireWildcard(require("./utils"));
25
-
26
- 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); }
27
-
28
- 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; }
29
-
15
+ var _utils = _interopRequireWildcard(require("./utils"));
16
+ var utils = _utils;
17
+ var _combineExports = _interopRequireDefault(require("./combineExports"));
18
+ var _helper = require("./helper");
19
+ var _generateJSAPIs = _interopRequireDefault(require("./generateJSAPIs"));
20
+ var _generateCompatibilities = _interopRequireWildcard(require("./generateCompatibilities"));
21
+ function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
22
+ function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
30
23
  /**
31
24
  * https://astexplorer.net/
32
25
  */
26
+
33
27
  var identifierPrefix = '__hylid_bridge__';
34
28
  var libraryName = 'hylid-bridge';
35
- var libraryDir = (0, _getLibraryDir.default)();
36
-
37
- function getTargets(customTargets) {
38
- var targets = customTargets || (process.env.HYLID_BRIDGE_TARGETS ? process.env.HYLID_BRIDGE_TARGETS.split(',') : []);
39
- return targets;
40
- }
41
-
42
- function isApiExists(name, target) {
43
- var targetSplit = target.split('|');
44
-
45
- if (targetSplit.length !== 2) {
46
- throw new Error("Wrong target configuration: ".concat(target, "."));
47
- }
48
-
49
- return _fsExtra.default.existsSync(_path.default.resolve(libraryDir, "./lib/clients/".concat(targetSplit[0], "/").concat(targetSplit[1], "/").concat(name, ".js")));
50
- }
51
-
52
- var _default = function _default(_, opts) {
53
- var targets = getTargets(opts === null || opts === void 0 ? void 0 : opts.targets);
29
+ var myLocalName = "".concat(identifierPrefix, "my__");
30
+ var _default = exports.default = function _default(core, opts) {
31
+ var _opts$libraryDir, _opts$transformMy, _opts$compact;
32
+ var libraryDir = (_opts$libraryDir = opts === null || opts === void 0 ? void 0 : opts.libraryDir) !== null && _opts$libraryDir !== void 0 ? _opts$libraryDir : (0, _getLibraryDir.default)();
33
+ var targets = (0, _helper.getTargets)(libraryDir, opts === null || opts === void 0 ? void 0 : opts.targets);
34
+ var userAppEnvPath = (0, _helper.getUserAppEnvPath)(opts === null || opts === void 0 ? void 0 : opts.appEnvPath);
35
+ var polyfillDir = opts === null || opts === void 0 ? void 0 : opts.polyfillDir;
36
+ var transformMy = (_opts$transformMy = opts === null || opts === void 0 ? void 0 : opts.transformMy) !== null && _opts$transformMy !== void 0 ? _opts$transformMy : false;
37
+ var compact = (_opts$compact = opts === null || opts === void 0 ? void 0 : opts.compact) !== null && _opts$compact !== void 0 ? _opts$compact : true;
38
+ // 生成 babel-compact 文件
39
+ compact && (0, _generateJSAPIs.default)(targets, libraryDir);
40
+ (0, _generateCompatibilities.default)(targets, libraryDir);
54
41
  return {
55
42
  name: 'babel-plugin-hylid-bridge',
56
43
  visitor: {
44
+ ImportDeclaration: function ImportDeclaration(path) {
45
+ if (!compact) return;
46
+ if (path.node.source.value === libraryName) {
47
+ path.node.source = core.types.stringLiteral("".concat(libraryName, "/babel-compact"));
48
+ }
49
+ },
50
+ ExportNamedDeclaration: function ExportNamedDeclaration(path) {
51
+ var _path$node$source;
52
+ if (!compact) return;
53
+ if (((_path$node$source = path.node.source) === null || _path$node$source === void 0 ? void 0 : _path$node$source.value) === libraryName) {
54
+ path.node.source = core.types.stringLiteral("".concat(libraryName, "/babel-compact"));
55
+ }
56
+ },
57
57
  MemberExpression: function MemberExpression(path, state) {
58
- var _this = this;
59
-
60
- var objectName = path.node.object.name;
61
- var propertyName = path.node.property.name;
62
-
63
- if (!targets || !targets.length || objectName !== 'my' || path.scope.hasBinding('my')) {
58
+ var _getNames = (0, _helper.getNames)(path.node, path.scope, state, targets),
59
+ objectName = _getNames.objectName,
60
+ propertyName = _getNames.propertyName;
61
+ if (propertyName === 'call' || objectName !== 'my' || !transformMy) {
64
62
  return;
65
63
  }
66
-
64
+ var newNode = core.types.cloneNode(path.node, true, true);
65
+ newNode.object = core.types.identifier(myLocalName);
67
66
  if (state.usedJSAPIList === 'all') {
67
+ path.replaceWith(newNode);
68
68
  return;
69
69
  }
70
-
71
- if (path.node.computed) {
70
+ if (!propertyName && path.node.computed) {
72
71
  state.usedJSAPIList = 'all';
73
- 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(this.file.opts.filename, "`."));
74
- } else {
72
+ utils.warn("Detect visiting the property of `my` with computed mode. Fallback to import all API codes of ".concat(targets.join(','), ". Current file path: `").concat(state.filename, "`."));
73
+ path.replaceWith(newNode);
74
+ return;
75
+ }
76
+ if (propertyName) {
75
77
  state.usedJSAPIList = state.usedJSAPIList || [];
76
78
  var name = propertyName;
77
-
78
- if (targets.every(function (target) {
79
- var targetSplit = target.split('|');
80
-
81
- if (!isApiExists(name, target)) {
82
- utils.warn("Can not find the API `".concat(name, "` 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(_this.file.opts.filename, "`."));
83
- return false;
84
- }
85
-
86
- return true;
87
- })) {
79
+ if ((0, _helper.isJSAPIInTargets)(name, targets, state.filename, libraryDir, polyfillDir)) {
88
80
  state.usedJSAPIList.push(name);
89
81
  } else {
90
82
  state.usedJSAPIList = 'all';
91
83
  }
84
+ path.replaceWith(newNode);
85
+ return;
86
+ }
87
+ },
88
+ CallExpression: function CallExpression(path, state) {
89
+ if (path.node.callee.type === 'Identifier' && path.node.callee.name === 'whichCanIUse') {
90
+ if (!state.whichCanIUseJsapiList) {
91
+ state.whichCanIUseJsapiList = [];
92
+ }
93
+ if (path.node.arguments[0].type === 'StringLiteral') {
94
+ state.whichCanIUseJsapiList.push(path.node.arguments[0].value);
95
+ } else {
96
+ // apiName 为非字符串类型,警告开发者
97
+ (0, _utils.warn)('WhichCanIUse warning: apiName must be a string literal and not a variable');
98
+ }
99
+ }
100
+ if (path.node.callee.type !== 'MemberExpression' || !transformMy) {
101
+ return;
102
+ }
103
+ var _getNames2 = (0, _helper.getNames)(path.node.callee, path.scope, state, targets),
104
+ objectName = _getNames2.objectName,
105
+ propertyName = _getNames2.propertyName;
106
+ if (objectName !== 'my' || propertyName !== 'call' || !path.node.arguments[0] || path.node.arguments[0].type !== 'StringLiteral') {
107
+ return;
108
+ }
109
+ var newNode = core.types.callExpression(
110
+ // @ts-ignore
111
+ babelTypes.memberExpression(babelTypes.identifier(myLocalName), babelTypes.identifier(path.node.arguments[0].value)), path.node.arguments.slice(1));
112
+ if (state.usedJSAPIList === 'all') {
113
+ path.replaceWith(newNode);
114
+ return;
115
+ }
116
+ state.usedJSAPIList = state.usedJSAPIList || [];
117
+ var name = path.node.arguments[0].value;
118
+ if ((0, _helper.isJSAPIInTargets)(name, targets, state.filename, libraryDir, polyfillDir)) {
119
+ state.usedJSAPIList.push(name);
120
+ } else {
121
+ state.usedJSAPIList = 'all';
92
122
  }
123
+ path.replaceWith(newNode);
93
124
  },
94
125
  Program: {
95
126
  exit: function exit(path, state) {
127
+ var _state$whichCanIUseJs;
128
+ if ((_state$whichCanIUseJs = state.whichCanIUseJsapiList) !== null && _state$whichCanIUseJs !== void 0 && _state$whichCanIUseJs.length) {
129
+ (0, _generateCompatibilities.filterWhichCanIUseJsapi)(state.whichCanIUseJsapiList);
130
+ }
96
131
  if (!state.usedJSAPIList) {
97
132
  return;
98
133
  }
99
-
100
134
  var usedJSAPIList = state.usedJSAPIList || [];
101
135
  var appEnvLocalName = "".concat(identifierPrefix, "appEnv__");
102
-
103
136
  if (path.scope.hasBinding(appEnvLocalName)) {
104
137
  return;
105
138
  }
106
-
107
- var nodes = [babelTypes.importDeclaration([babelTypes.importDefaultSpecifier(babelTypes.identifier(appEnvLocalName))], babelTypes.stringLiteral("".concat(libraryName, "/lib/appEnv")))];
108
-
139
+ var innerAppEnvLocalName = "".concat(identifierPrefix, "innerAppEnv__");
140
+ var userAppEnvLocalName = "".concat(identifierPrefix, "userAppEnv__");
141
+ var nodes = [babelTypes.importDeclaration([babelTypes.importDefaultSpecifier(babelTypes.identifier(innerAppEnvLocalName))], babelTypes.stringLiteral("".concat(libraryName, "/lib/appEnv")))];
142
+ if (userAppEnvPath) {
143
+ var relativePath = _path.default.relative(_path.default.dirname(state.filename), userAppEnvPath.replace(/\.ts$/, ''));
144
+ nodes.push(babelTypes.importDeclaration([babelTypes.importDefaultSpecifier(babelTypes.identifier(userAppEnvLocalName))], babelTypes.stringLiteral(relativePath.startsWith('../') ? relativePath : "./".concat(relativePath))));
145
+ } else {
146
+ nodes.push(babelTypes.variableDeclaration('var', [babelTypes.variableDeclarator(babelTypes.identifier(userAppEnvLocalName), babelTypes.objectExpression([]))]));
147
+ }
148
+ var objectSpreadName = "".concat(identifierPrefix, "objectSpread__");
149
+ 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)]))]));
109
150
  if (usedJSAPIList === 'all') {
110
151
  nodes.push.apply(nodes, (0, _toConsumableArray2.default)(targets.map(function (target) {
111
- var targetSplit = target.split('|');
112
- 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")));
152
+ var targetSplit = (0, _helper.splitTarget)(target);
153
+ var innerIndexPath = "".concat(libraryName, "/lib/clients/").concat(targetSplit[0], "/").concat(targetSplit[1], "/index");
154
+ var polyfillIndexPath = polyfillDir && _path.default.resolve(polyfillDir, targetSplit[0], targetSplit[1], 'index');
155
+ var normalizedIndexPath = polyfillIndexPath && (_fsExtra.default.existsSync("".concat(polyfillIndexPath, ".js")) || _fsExtra.default.existsSync("".concat(polyfillIndexPath, ".ts"))) ? (0, _combineExports.default)(require.resolve(innerIndexPath), polyfillIndexPath) : innerIndexPath;
156
+ return babelTypes.importDeclaration([babelTypes.importDefaultSpecifier(babelTypes.identifier("".concat(identifierPrefix).concat(targetSplit[0], "_").concat(targetSplit[1], "_my__")))], babelTypes.stringLiteral(normalizedIndexPath));
113
157
  })));
114
-
115
- var buildElseIf = function buildElseIf(targetList) {
158
+ var _buildElseIf = function buildElseIf(targetList) {
116
159
  if (!targetList.length) {
117
160
  return;
118
161
  }
119
-
120
162
  var target = targetList[0];
121
- var targetSplit = target.split('|');
122
- 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('my'), babelTypes.identifier("".concat(identifierPrefix).concat(targetSplit[0], "_").concat(targetSplit[1], "_my__"))))]), buildElseIf(targetList.slice(1)));
163
+ var targetSplit = (0, _helper.splitTarget)(target);
164
+ return babelTypes.ifStatement(babelTypes.identifier("".concat(appEnvLocalName, ".").concat((0, _helper.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)));
123
165
  };
124
-
125
- nodes.push(babelTypes.variableDeclaration('var', [babelTypes.variableDeclarator(babelTypes.identifier('my'))])); // Do not generate the `if statement` when there is just one target.
126
-
166
+ nodes.push(babelTypes.variableDeclaration('var', [babelTypes.variableDeclarator(babelTypes.identifier(myLocalName))]));
167
+ // Do not generate the `if statement` when there is just one target.
127
168
  if (targets.length === 1) {
128
- var targetSplit = targets[0].split('|');
129
- nodes.push(babelTypes.expressionStatement(babelTypes.assignmentExpression('=', babelTypes.identifier('my'), babelTypes.identifier("".concat(identifierPrefix).concat(targetSplit[0], "_").concat(targetSplit[1], "_my__")))));
169
+ var targetSplit = (0, _helper.splitTarget)(targets[0]);
170
+ nodes.push(babelTypes.expressionStatement(babelTypes.assignmentExpression('=', babelTypes.identifier(myLocalName), babelTypes.identifier("".concat(identifierPrefix).concat(targetSplit[0], "_").concat(targetSplit[1], "_my__")))));
130
171
  } else {
131
- var elseIfNode = buildElseIf(targets);
172
+ var elseIfNode = _buildElseIf(targets);
132
173
  elseIfNode && nodes.push(elseIfNode);
133
174
  }
134
175
  } else if (usedJSAPIList.length) {
135
176
  var normalizedJSAPIList = _lodash.default.uniq(usedJSAPIList);
136
-
137
177
  normalizedJSAPIList.forEach(function (name) {
138
178
  targets.forEach(function (target) {
139
- var localName = "".concat(identifierPrefix).concat(target, "_").concat(name, "__");
140
- var targetSplit = target.split('|');
141
- var n = babelTypes.importDeclaration([babelTypes.importDefaultSpecifier(babelTypes.identifier(localName))], babelTypes.stringLiteral("".concat(libraryName, "/lib/clients/").concat(targetSplit[0], "/").concat(targetSplit[1], "/").concat(name)));
179
+ var targetSplit = (0, _helper.splitTarget)(target);
180
+ var localName = "".concat(identifierPrefix).concat(targetSplit[0], "_").concat(targetSplit[1], "_").concat(name, "__");
181
+ var innerSourcePath = "".concat(libraryName, "/lib/clients/").concat(targetSplit[0], "/").concat(targetSplit[1], "/").concat(name);
182
+ var userSourcePath = polyfillDir ? _path.default.resolve(polyfillDir, targetSplit[0], targetSplit[1], name) : undefined;
183
+ var n = babelTypes.importDeclaration([babelTypes.importDefaultSpecifier(babelTypes.identifier(localName))], babelTypes.stringLiteral(userSourcePath && (_fsExtra.default.existsSync("".concat(userSourcePath, ".js")) || _fsExtra.default.existsSync("".concat(userSourcePath, ".ts"))) ? userSourcePath : innerSourcePath));
142
184
  nodes.push(n);
143
185
  });
144
186
  });
145
-
146
- var _buildElseIf = function _buildElseIf(targetList) {
187
+ var _buildElseIf2 = function buildElseIf(targetList) {
147
188
  if (!targetList.length) {
148
189
  return;
149
190
  }
150
-
151
191
  var target = targetList[0];
152
- var targetSplit = target.split('|');
192
+ var targetSplit = (0, _helper.splitTarget)(target);
153
193
  var propertyList = normalizedJSAPIList.map(function (name) {
154
194
  return babelTypes.objectProperty(babelTypes.identifier(name), babelTypes.identifier("".concat(identifierPrefix).concat(targetSplit[0], "_").concat(targetSplit[1], "_").concat(name, "__")));
155
195
  });
156
- 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('my'), babelTypes.objectExpression(propertyList)))]), _buildElseIf(targetList.slice(1)));
196
+ return babelTypes.ifStatement(babelTypes.identifier("".concat(appEnvLocalName, ".").concat((0, _helper.camelCase)("is_".concat(targetSplit[0], "_").concat(targetSplit[1])))), babelTypes.blockStatement([babelTypes.expressionStatement(babelTypes.assignmentExpression('=', babelTypes.identifier(myLocalName), babelTypes.objectExpression(propertyList)))]), _buildElseIf2(targetList.slice(1)));
157
197
  };
158
-
159
- nodes.push(babelTypes.variableDeclaration('var', [babelTypes.variableDeclarator(babelTypes.identifier('my'))])); // Do not generate the `if statement` when there is just one target.
160
-
198
+ nodes.push(babelTypes.variableDeclaration('var', [babelTypes.variableDeclarator(babelTypes.identifier(myLocalName))]));
199
+ // Do not generate the `if statement` when there is just one target.
161
200
  if (targets.length === 1) {
162
- var _targetSplit = targets[0].split('|');
163
-
201
+ var _targetSplit = (0, _helper.splitTarget)(targets[0]);
164
202
  var propertyList = normalizedJSAPIList.map(function (name) {
165
203
  return babelTypes.objectProperty(babelTypes.identifier(name), babelTypes.identifier("".concat(identifierPrefix).concat(_targetSplit[0], "_").concat(_targetSplit[1], "_").concat(name, "__")));
166
204
  });
167
- nodes.push(babelTypes.expressionStatement(babelTypes.assignmentExpression('=', babelTypes.identifier('my'), babelTypes.objectExpression(propertyList))));
205
+ nodes.push(babelTypes.expressionStatement(babelTypes.assignmentExpression('=', babelTypes.identifier(myLocalName), babelTypes.objectExpression(propertyList))));
168
206
  } else {
169
- var _elseIfNode = _buildElseIf(targets);
170
-
207
+ var _elseIfNode = _buildElseIf2(targets);
171
208
  _elseIfNode && nodes.push(_elseIfNode);
172
209
  }
173
210
  }
174
-
175
211
  if (nodes.length) {
176
212
  path.unshiftContainer('body', nodes);
177
213
  }
214
+ if (targets.length && (usedJSAPIList === 'all' || usedJSAPIList.length)) {
215
+ utils.log("Successfully inject the Hylid-bridge into ".concat(state.filename, " to support the targets: ").concat(targets.join(','), "."));
216
+ }
178
217
  }
179
218
  }
180
219
  }
181
220
  };
182
- };
183
-
184
- exports.default = _default;
221
+ };
package/lib/utils.js CHANGED
@@ -1,42 +1,31 @@
1
1
  "use strict";
2
2
 
3
3
  var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
-
5
4
  Object.defineProperty(exports, "__esModule", {
6
5
  value: true
7
6
  });
8
7
  exports.error = error;
9
8
  exports.log = log;
10
9
  exports.warn = warn;
11
-
12
10
  var _chalk = _interopRequireDefault(require("chalk"));
13
-
14
11
  function log() {
15
12
  var _console;
16
-
17
13
  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
18
14
  args[_key] = arguments[_key];
19
15
  }
20
-
21
16
  (_console = console).log.apply(_console, [_chalk.default.bold.green('[LOG]')].concat(args));
22
17
  }
23
-
24
18
  function error() {
25
19
  var _console2;
26
-
27
20
  for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
28
21
  args[_key2] = arguments[_key2];
29
22
  }
30
-
31
23
  (_console2 = console).error.apply(_console2, [_chalk.default.bold.red('[ERROR]')].concat(args));
32
24
  }
33
-
34
25
  function warn() {
35
26
  var _console3;
36
-
37
27
  for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
38
28
  args[_key3] = arguments[_key3];
39
29
  }
40
-
41
30
  (_console3 = console).error.apply(_console3, [_chalk.default.bold.yellow('[WARN]')].concat(args));
42
31
  }
package/package.json CHANGED
@@ -1,31 +1,28 @@
1
1
  {
2
2
  "name": "babel-plugin-hylid-bridge",
3
- "version": "0.0.1",
3
+ "version": "0.0.2-dev.1",
4
4
  "description": "babel-plugin-hylid-bridge",
5
5
  "main": "lib/index.js",
6
- "scripts": {
7
- "build": "gulp build",
8
- "dev": "gulp dev"
9
- },
10
6
  "files": [
11
7
  "lib"
12
8
  ],
13
9
  "keywords": [],
14
10
  "license": "MIT",
15
11
  "dependencies": {
16
- "@babel/core": "^7.15.6",
17
- "@babel/types": "^7.15.6",
18
- "@types/fs-extra": "^9.0.13",
19
- "@types/lodash": "^4.14.176",
20
- "chalk": "^4.1.2",
21
- "fs-extra": "^10.0.0",
22
- "lodash": "^4.17.21"
12
+ "@babel/core": "7.18.2",
13
+ "@babel/runtime": "7.18.9",
14
+ "@babel/types": "7.18.10",
15
+ "@types/fs-extra": "9.0.13",
16
+ "@types/lodash": "4.14.182",
17
+ "chalk": "3.0.0",
18
+ "fs-extra": "10.1.0",
19
+ "hash-it": "^6.0.0",
20
+ "lodash": "4.17.21"
23
21
  },
24
22
  "devDependencies": {
25
- "gulp": "4.0.2",
26
- "gulp-plumber": "^1.2.1",
27
- "gulp-babel": "8.0.0",
28
- "gulp-typescript": "5.0.1"
23
+ "@types/babel-plugin-tester": "^9.0.7",
24
+ "babel-plugin-tester": "^10.1.0",
25
+ "hylid-bridge": "^0.0.2-dev.1"
29
26
  },
30
27
  "sideEffects": false,
31
28
  "registry": "https://registry.npmjs.org/"
package/CHANGELOG.md DELETED
File without changes