| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746 |
- "use strict";
- var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.resolvePlatformIndex = exports.resolvePlatformIndexFilename = exports.resolveRootInterface = exports.resolveRootIndex = exports.genComponentsCode = exports.genProxyCode = void 0;
- const fs_1 = __importDefault(require("fs"));
- const path_1 = __importDefault(require("path"));
- const shared_1 = require("@vue/shared");
- const utils_1 = require("./utils");
- const shared_2 = require("./shared");
- const stacktrace_1 = require("./stacktrace");
- async function genProxyCode(module, options) {
- const { name, is_uni_modules, format, moduleName, moduleType } = options;
- options.inputDir = options.inputDir || process.env.UNI_INPUT_DIR;
- if (!options.meta) {
- options.meta = { exports: {}, types: {} };
- }
- options.types = await parseInterfaceTypes(module, options);
- options.meta.types = parseMetaTypes(options.types);
- const decls = await parseModuleDecls(module, options);
- return `
- const { registerUTSInterface, initUTSProxyClass, initUTSProxyFunction, initUTSPackageName, initUTSIndexClassName, initUTSClassName } = uni
- const name = '${name}'
- const moduleName = '${moduleName || ''}'
- const moduleType = '${moduleType || ''}'
- const errMsg = \`${utils_1.ERR_MSG_PLACEHOLDER}\`
- const is_uni_modules = ${is_uni_modules}
- const pkg = /*#__PURE__*/ initUTSPackageName(name, is_uni_modules)
- const cls = /*#__PURE__*/ initUTSIndexClassName(name, is_uni_modules)
- ${format === "cjs" /* FORMATS.CJS */
- ? `
- const exports = { __esModule: true }
- `
- : ''}
- ${genComponentsCode(format, options.androidComponents || {}, options.iosComponents || {})}
- ${genModuleCode(decls, format, options.pluginRelativeDir, options.meta)}
- `;
- }
- exports.genProxyCode = genProxyCode;
- function parseMetaTypes(types) {
- let res = {};
- types.class.forEach((n) => {
- res[n] = 'class';
- });
- Object.keys(types.fn).forEach((n) => {
- res[n] = 'function';
- });
- Object.keys(types.interface).forEach((n) => {
- res[n] = 'interface';
- });
- return res;
- }
- function genComponentsCode(format = "es" /* FORMATS.ES */, androidComponents, iosComponents) {
- const codes = [];
- Object.keys(Object.assign({}, androidComponents, iosComponents)).forEach((name) => {
- if (format === "cjs" /* FORMATS.CJS */) {
- codes.push(`exports.${(0, shared_1.capitalize)((0, shared_1.camelize)(name))}Component = {}`);
- }
- else {
- codes.push(`export const ${(0, shared_1.capitalize)((0, shared_1.camelize)(name))}Component = {}`);
- }
- });
- return codes.join('\n');
- }
- exports.genComponentsCode = genComponentsCode;
- function resolveRootIndex(module, options) {
- const filename = path_1.default.resolve(module, options.is_uni_modules ? 'utssdk' : '', `index${options.extname}`);
- return fs_1.default.existsSync(filename) && filename;
- }
- exports.resolveRootIndex = resolveRootIndex;
- function resolveRootInterface(module, options) {
- const filename = path_1.default.resolve(module, options.is_uni_modules ? 'utssdk' : '', `interface${options.extname}`);
- return fs_1.default.existsSync(filename) && filename;
- }
- exports.resolveRootInterface = resolveRootInterface;
- function resolvePlatformIndexFilename(platform, module, options) {
- return path_1.default.resolve(module, options.is_uni_modules ? 'utssdk' : '', platform, `index${options.extname}`);
- }
- exports.resolvePlatformIndexFilename = resolvePlatformIndexFilename;
- function resolvePlatformIndex(platform, module, options) {
- const filename = resolvePlatformIndexFilename(platform, module, options);
- return fs_1.default.existsSync(filename) && filename;
- }
- exports.resolvePlatformIndex = resolvePlatformIndex;
- function exportDefaultCode(format) {
- return format === "es" /* FORMATS.ES */
- ? 'export default /*#__PURE__*/ '
- : 'exports.default = ';
- }
- function exportVarCode(format, kind) {
- if (format === "es" /* FORMATS.ES */) {
- return `export ${kind} `;
- }
- return `exports.`;
- }
- function isClassReturnOptions(value) {
- return ((0, shared_1.isPlainObject)(value) &&
- value.type === 'interface' &&
- (0, shared_1.isString)(value.options));
- }
- function genClassOptionsCode(options) {
- return JSON.stringify(options, (key, value) => {
- if (key === 'return' && isClassReturnOptions(value)) {
- return { type: 'interface', options: `${value.options}Options` };
- }
- return value;
- });
- }
- function genModuleCode(decls, format = "es" /* FORMATS.ES */, pluginRelativeDir, meta) {
- const codes = [];
- const exportDefault = exportDefaultCode(format);
- const exportConst = exportVarCode(format, 'const');
- decls.forEach((decl) => {
- if (decl.type === 'InterfaceDeclaration') {
- meta.exports[decl.cls] = 'interface';
- codes.push(`registerUTSInterface('${decl.cls}Options',Object.assign({ moduleName, moduleType, errMsg, package: pkg, class: initUTSClassName(name, '${decl.cls}ByJsProxy', is_uni_modules) }, ${genClassOptionsCode(decl.options)} ))`);
- }
- else if (decl.type === 'Class') {
- meta.exports[decl.cls] = decl.isVar ? 'var' : 'class';
- if (decl.isDefault) {
- codes.push(`${exportDefault}initUTSProxyClass(Object.assign({ moduleName, moduleType, errMsg, package: pkg, class: initUTSClassName(name, '${decl.cls}ByJs', is_uni_modules) }, ${genClassOptionsCode(decl.options)} ))`);
- }
- else {
- codes.push(`${exportConst}${decl.cls} = /*#__PURE__*/ initUTSProxyClass(Object.assign({ moduleName, moduleType, errMsg, package: pkg, class: initUTSClassName(name, '${decl.cls}ByJs', is_uni_modules) }, ${genClassOptionsCode(decl.options)} ))`);
- }
- }
- else if (decl.type === 'FunctionDeclaration') {
- meta.exports[decl.method] = decl.isVar ? 'var' : 'function';
- const returnOptions = decl.return
- ? { type: decl.return.type, options: decl.return.options + 'Options' }
- : '';
- if (decl.isDefault) {
- codes.push(`${exportDefault}initUTSProxyFunction(${decl.async}, { moduleName, moduleType, errMsg, main: true, package: pkg, class: cls, name: '${decl.method}ByJs', params: ${JSON.stringify(decl.params)}, return: ${JSON.stringify(returnOptions)}})`);
- }
- else {
- codes.push(`${exportConst}${decl.method} = /*#__PURE__*/ initUTSProxyFunction(${decl.async}, { moduleName, moduleType, errMsg, main: true, package: pkg, class: cls, name: '${decl.method}ByJs', params: ${JSON.stringify(decl.params)}, return: ${JSON.stringify(returnOptions)}})`);
- }
- }
- else if (decl.type === 'VariableDeclaration') {
- decl.declarations.forEach((d) => {
- meta.exports[d.id.value] = 'var';
- });
- if (format === "es" /* FORMATS.ES */) {
- codes.push(`export ${decl.kind} ${decl.declarations
- .map((d) => `${d.id.value} = ${genInitCode(d.init)}`)
- .join(', ')}`);
- }
- else if (format === "cjs" /* FORMATS.CJS */) {
- codes.push(`${decl.kind} ${decl.declarations
- .map((d) => `${d.id.value} = ${genInitCode(d.init)}`)
- .join(', ')}`);
- const exportVar = exportVarCode(format, decl.kind);
- decl.declarations.forEach((d) => {
- const name = d.id.value;
- codes.push(`${exportVar}${name} = ${name}`);
- });
- }
- }
- });
- if (format === "cjs" /* FORMATS.CJS */) {
- codes.push(`uni.registerUTSPlugin('${(0, shared_2.normalizePath)(pluginRelativeDir)}', exports)`);
- }
- return codes.join(`\n`);
- }
- /**
- * 解析接口文件中定义的类型信息
- * @param module
- * @param options
- * @returns
- */
- async function parseInterfaceTypes(module, options) {
- const interfaceFilename = resolveRootInterface(module, options);
- if (!interfaceFilename) {
- return {
- interface: {},
- class: [],
- fn: {},
- };
- }
- // 懒加载 uts 编译器
- // eslint-disable-next-line no-restricted-globals
- const { parse } = require('@dcloudio/uts');
- let ast = null;
- try {
- ast = await parse(fs_1.default.readFileSync(interfaceFilename, 'utf8'), {
- filename: (0, utils_1.relative)(interfaceFilename, options.inputDir),
- noColor: !(0, utils_1.isColorSupported)(),
- });
- }
- catch (e) {
- console.error((0, stacktrace_1.parseUTSSyntaxError)(e, options.inputDir));
- }
- return parseAstTypes(ast, true);
- }
- function parseAstTypes(ast, isInterface) {
- const interfaceTypes = {};
- const classTypes = [];
- const fnTypes = {};
- const exportNamed = [];
- if (ast) {
- if (isInterface) {
- ast.body.filter((node) => {
- if (node.type === 'ExportNamedDeclaration') {
- node.specifiers.forEach((s) => {
- if (s.type === 'ExportSpecifier') {
- if (s.exported) {
- if (s.exported.type === 'Identifier') {
- exportNamed.push(s.exported.value);
- }
- }
- else {
- exportNamed.push(s.orig.value);
- }
- }
- });
- }
- });
- }
- ast.body.filter((node) => {
- if (node.type === 'ExportDeclaration') {
- if (node.declaration.type === 'TsTypeAliasDeclaration') {
- parseTypes(node.declaration, classTypes, fnTypes);
- }
- else if (node.declaration.type === 'TsInterfaceDeclaration') {
- interfaceTypes[node.declaration.id.value] = {
- returned: false,
- decl: node.declaration,
- };
- }
- }
- else if (node.type === 'TsTypeAliasDeclaration') {
- if (!isInterface || exportNamed.includes(node.id.value)) {
- parseTypes(node, classTypes, fnTypes);
- }
- }
- else if (node.type === 'TsInterfaceDeclaration') {
- interfaceTypes[node.id.value] = {
- returned: false,
- decl: node,
- };
- }
- });
- }
- return {
- interface: interfaceTypes,
- class: classTypes,
- fn: fnTypes,
- };
- }
- function parseTypes(decl, classTypes, fnTypes) {
- switch (decl.typeAnnotation.type) {
- // export type ShowLoading = ()=>void
- case 'TsFunctionType':
- const params = createParams(decl.typeAnnotation.params);
- if (params.length) {
- fnTypes[decl.id.value] = params;
- }
- else {
- fnTypes[decl.id.value] = [];
- }
- break;
- // export type ShowLoadingOptions = {}
- case 'TsTypeLiteral':
- classTypes.push(decl.id.value);
- }
- }
- function createParams(tsParams) {
- const params = [];
- tsParams.forEach((pat) => {
- if (pat.type === 'Identifier') {
- params.push({
- type: 'Parameter',
- pat,
- span: {},
- });
- }
- });
- return params;
- }
- async function parseModuleDecls(module, options) {
- // 优先合并 ios + android,如果没有,查找根目录 index.uts
- const iosDecls = await parseFile(resolvePlatformIndex('app-ios', module, options), options);
- const androidDecls = await parseFile(resolvePlatformIndex('app-android', module, options), options);
- // 优先使用 app-ios,因为 app-ios 平台函数类型需要正确的参数列表
- const decls = mergeDecls(androidDecls, iosDecls);
- // 如果没有平台特有,查找 root index.uts
- if (!decls.length) {
- return await parseFile(resolveRootIndex(module, options), options);
- }
- return decls;
- }
- function mergeDecls(from, to) {
- from.forEach((item) => {
- if (item.type === 'InterfaceDeclaration') {
- if (!to.find((toItem) => toItem.type === 'InterfaceDeclaration' && toItem.cls === item.cls)) {
- to.push(item);
- }
- }
- else if (item.type === 'Class') {
- if (!to.find((toItem) => toItem.type === 'Class' &&
- toItem.cls === item.cls &&
- toItem.isDefault === item.isDefault)) {
- to.push(item);
- }
- }
- else if (item.type === 'FunctionDeclaration') {
- if (!to.find((toItem) => toItem.type === 'FunctionDeclaration' &&
- toItem.method === item.method &&
- toItem.isDefault === item.isDefault)) {
- to.push(item);
- }
- }
- else if (item.type === 'VariableDeclaration' &&
- item.declarations.length === 1) {
- if (!to.find((toItem) => {
- if (toItem.type === 'VariableDeclaration' &&
- toItem.declarations.length === 1) {
- const toDecl = toItem.declarations[0].id;
- const decl = item.declarations[0].id;
- return (toDecl.type === 'Identifier' &&
- decl.type === 'Identifier' &&
- toDecl.value === decl.value);
- }
- return false;
- })) {
- to.push(item);
- }
- }
- });
- return to;
- }
- async function parseFile(filename, options) {
- if (filename) {
- return parseCode(fs_1.default.readFileSync(filename, 'utf8'), options.namespace, options.types, filename, options.inputDir);
- }
- return [];
- }
- async function parseCode(code, namespace, types, filename, inputDir) {
- // 懒加载 uts 编译器
- // eslint-disable-next-line no-restricted-globals
- const { parse } = require('@dcloudio/uts');
- try {
- const ast = await parse(code, {
- filename: (0, utils_1.relative)(filename, inputDir),
- noColor: !(0, utils_1.isColorSupported)(),
- });
- return parseAst(ast, (0, utils_1.createResolveTypeReferenceName)(namespace, ast, types.class), types);
- }
- catch (e) {
- console.error((0, stacktrace_1.parseUTSSyntaxError)(e, inputDir));
- }
- return [];
- }
- function mergeAstTypes(to, from) {
- if (from.class.length) {
- to.class = [...new Set(...[...to.class, ...from.class])];
- }
- if (Object.keys(from.fn).length) {
- for (const name in from.fn) {
- if (!(0, shared_1.hasOwn)(to.fn, name)) {
- to.fn[name] = from.fn[name];
- }
- }
- }
- if (Object.keys(from.interface).length) {
- for (const name in from.interface) {
- if (!(0, shared_1.hasOwn)(to.interface, name)) {
- to.interface[name] = from.interface[name];
- }
- }
- }
- }
- function parseAst(ast, resolveTypeReferenceName, types) {
- const decls = [];
- mergeAstTypes(types, parseAstTypes(ast, false));
- ast.body.forEach((item) => {
- if (item.type === 'ExportDeclaration') {
- const decl = item.declaration;
- switch (decl.type) {
- case 'FunctionDeclaration':
- decls.push(genFunctionDeclaration(types, decl, resolveTypeReferenceName, false));
- break;
- case 'ClassDeclaration':
- decls.push(genClassDeclaration(types, decl, resolveTypeReferenceName, false));
- break;
- case 'VariableDeclaration':
- const varDecl = genVariableDeclaration(types, decl, resolveTypeReferenceName);
- if (varDecl) {
- decls.push(varDecl);
- }
- break;
- }
- }
- else if (item.type === 'ExportDefaultDeclaration') {
- const decl = item.decl;
- if (decl.type === 'ClassExpression') {
- if (decl.identifier) {
- // export default class test{}
- decls.push(genClassDeclaration(types, decl, resolveTypeReferenceName, true));
- }
- }
- else if (decl.type === 'FunctionExpression') {
- if (decl.identifier) {
- decls.push(genFunctionDeclaration(types, decl, resolveTypeReferenceName, true));
- }
- }
- }
- });
- const interfaces = [];
- Object.keys(types.interface).forEach((name) => {
- const options = types.interface[name];
- if (options.returned) {
- interfaces.push(genInterfaceDeclaration(types, options.decl, resolveTypeReferenceName));
- }
- });
- return [...interfaces, ...decls];
- }
- function isReturnPromise(anno) {
- if (!anno) {
- return false;
- }
- const { typeAnnotation } = anno;
- return (typeAnnotation.type === 'TsTypeReference' &&
- typeAnnotation.typeName.type === 'Identifier' &&
- typeAnnotation.typeName.value === 'Promise');
- }
- function genProxyFunction(method, async, params, ret = '', isDefault = false, isVar = false) {
- return {
- type: 'FunctionDeclaration',
- method,
- async,
- params,
- return: ret ? { type: 'interface', options: ret } : undefined,
- isDefault,
- isVar,
- };
- }
- function genProxyClass(cls, options, isDefault = false, isVar = false) {
- return { type: 'Class', cls, options, isDefault, isVar };
- }
- function resolveIdentifierDefaultValue(ident) {
- if (ident.type === 'NullLiteral') {
- return 'UTSNull';
- }
- else if (ident.type === 'StringLiteral' ||
- ident.type === 'NumericLiteral' ||
- ident.type === 'BooleanLiteral') {
- return ident.value;
- }
- return null;
- }
- function resolveType(types, typeAnnotation, resolveTypeReferenceName) {
- if (typeAnnotation.type === 'TsKeywordType') {
- return typeAnnotation.kind;
- }
- else if (typeAnnotation.type === 'TsFunctionType') {
- return 'UTSCallback';
- }
- else if (typeAnnotation.type === 'TsTypeReference' &&
- typeAnnotation.typeName.type === 'Identifier') {
- if ((0, shared_1.hasOwn)(types.fn, typeAnnotation.typeName.value)) {
- return 'UTSCallback';
- }
- return resolveTypeReferenceName(typeAnnotation.typeName.value);
- }
- else if (typeAnnotation.type === 'TsParenthesizedType') {
- return resolveType(types, typeAnnotation.typeAnnotation, resolveTypeReferenceName);
- }
- else if (typeAnnotation.type === 'TsUnionType') {
- for (const type of typeAnnotation.types) {
- if (type.type === 'TsKeywordType') {
- continue;
- }
- return resolveType(types, type, resolveTypeReferenceName);
- }
- }
- return '';
- }
- function resolveIdentifierType(types, ident, resolveTypeReferenceName) {
- if (ident.typeAnnotation) {
- return resolveType(types, ident.typeAnnotation.typeAnnotation, resolveTypeReferenceName);
- }
- return '';
- }
- function resolveFunctionParams(types, params, resolveTypeReferenceName) {
- const result = [];
- params.forEach(({ pat }) => {
- if (pat.type === 'Identifier') {
- result.push({
- name: pat.value,
- type: resolveIdentifierType(types, pat, resolveTypeReferenceName),
- });
- }
- else if (pat.type === 'AssignmentPattern') {
- if (pat.left.type === 'Identifier') {
- const param = {
- name: pat.left.value,
- type: resolveIdentifierType(types, pat.left, resolveTypeReferenceName),
- };
- const defaultValue = resolveIdentifierDefaultValue(pat.right);
- if (defaultValue !== null) {
- param.default = defaultValue;
- }
- result.push(param);
- }
- }
- else {
- result.push({ name: '', type: '' });
- }
- });
- return result;
- }
- function parseReturnInterface(types, returnType) {
- switch (returnType.type) {
- case 'TsTypeReference':
- if (returnType.typeName.type === 'Identifier') {
- if ((0, shared_1.hasOwn)(types.interface, returnType.typeName.value)) {
- types.interface[returnType.typeName.value].returned = true;
- return returnType.typeName.value;
- }
- }
- break;
- case 'TsUnionType':
- for (const type of returnType.types) {
- if (type.type === 'TsKeywordType') {
- continue;
- }
- return parseReturnInterface(types, type);
- }
- break;
- case 'TsParenthesizedType':
- return parseReturnInterface(types, returnType.typeAnnotation);
- }
- return '';
- }
- function genFunctionDeclaration(types, decl, resolveTypeReferenceName, isDefault = false, isVar = false) {
- return genProxyFunction(decl.identifier.value, decl.async || isReturnPromise(decl.returnType), resolveFunctionParams(types, decl.params, resolveTypeReferenceName), decl.returnType
- ? parseReturnInterface(types, decl.returnType.typeAnnotation)
- : '', isDefault, isVar);
- }
- function genInterfaceDeclaration(types, decl, resolveTypeReferenceName) {
- const cls = decl.id.value;
- const methods = {};
- const props = [];
- decl.body.body.forEach((item) => {
- if (item.type === 'TsMethodSignature') {
- if (item.key.type === 'Identifier') {
- let returnOptions = {};
- if (item.typeAnn) {
- let returnInterface = parseReturnInterface(types, item.typeAnn.typeAnnotation);
- if (returnInterface) {
- returnOptions = {
- type: 'interface',
- options: returnInterface,
- };
- }
- }
- const name = item.key.value;
- const value = {
- async: isReturnPromise(item.typeAnn),
- params: resolveFunctionParams(types, tsParamsToParams(item.params), resolveTypeReferenceName),
- return: returnOptions,
- };
- methods[name + 'ByJs'] = value;
- }
- }
- else if (item.type === 'TsPropertySignature') {
- if (item.key.type === 'Identifier') {
- props.push(item.key.value);
- }
- }
- });
- return {
- type: 'InterfaceDeclaration',
- cls,
- options: {
- methods,
- props,
- },
- };
- }
- function tsParamsToParams(tsParams) {
- const params = [];
- tsParams.forEach((p) => {
- if (p.type === 'Identifier') {
- params.push({
- type: 'Parameter',
- pat: p,
- span: {},
- });
- }
- });
- return params;
- }
- function genClassDeclaration(types, decl, resolveTypeReferenceName, isDefault = false) {
- const cls = decl.identifier.value;
- const constructor = { params: [] };
- const methods = {};
- const staticMethods = {};
- const props = [];
- const staticProps = [];
- decl.body.forEach((item) => {
- if (item.type === 'Constructor') {
- constructor.params = resolveFunctionParams(types, item.params, resolveTypeReferenceName);
- }
- else if (item.type === 'ClassMethod') {
- if (item.key.type === 'Identifier') {
- let returnOptions = {};
- if (item.function.returnType) {
- let returnInterface = parseReturnInterface(types, item.function.returnType.typeAnnotation);
- if (returnInterface) {
- returnOptions = {
- type: 'interface',
- options: returnInterface,
- };
- }
- }
- const name = item.key.value;
- const value = {
- async: item.function.async || isReturnPromise(item.function.returnType),
- params: resolveFunctionParams(types, item.function.params, resolveTypeReferenceName),
- returnOptions,
- };
- if (item.isStatic) {
- staticMethods[name + 'ByJs'] = value;
- }
- else {
- methods[name + 'ByJs'] = value;
- }
- }
- }
- else if (item.type === 'ClassProperty') {
- if (item.key.type === 'Identifier') {
- if (item.isStatic) {
- staticProps.push(item.key.value);
- }
- else {
- props.push(item.key.value);
- }
- }
- }
- });
- return genProxyClass(cls, { constructor, methods, staticMethods, props, staticProps }, isDefault);
- }
- function genInitCode(expr) {
- switch (expr.type) {
- case 'BooleanLiteral':
- return expr.value + '';
- case 'NumericLiteral':
- return expr.value + '';
- case 'StringLiteral':
- return expr.value;
- }
- return '';
- }
- function genVariableDeclaration(types, decl, resolveTypeReferenceName) {
- // 目前仅支持 const 的 boolean,number,string
- const lits = ['BooleanLiteral', 'NumericLiteral', 'StringLiteral'];
- if (decl.kind === 'const' &&
- !decl.declarations.find((d) => {
- if (d.id.type !== 'Identifier') {
- return true;
- }
- if (!d.init) {
- return true;
- }
- const type = d.init.type;
- if (!lits.includes(type)) {
- return true;
- }
- return false;
- })) {
- return decl;
- }
- if (decl.declarations.length === 1) {
- // 识别是否是定义的 function,如:export const showToast:ShowToast = ()=>{}
- const { id, init } = decl.declarations[0];
- if (id.type === 'Identifier' &&
- init &&
- (init.type === 'ArrowFunctionExpression' ||
- init.type === 'FunctionExpression')) {
- // 根据类型信息查找参数列表
- let params;
- const typeAnn = id.typeAnnotation;
- if (typeAnn && typeAnn.typeAnnotation.type === 'TsTypeReference') {
- const { typeName } = typeAnn.typeAnnotation;
- if (typeName.type === 'Identifier') {
- const value = types.fn[typeName.value];
- if ((0, shared_1.isArray)(value)) {
- params = value;
- }
- }
- }
- return genFunctionDeclaration(types, createFunctionDeclaration(id.value, init, params), resolveTypeReferenceName, false, true);
- }
- }
- }
- // function createBindingIdentifier(name: string, typeAnnotation?: TsTypeAnnotation): BindingIdentifier {
- // return {
- // type: 'Identifier',
- // value: name,
- // optional: false,
- // span: {} as Span,
- // typeAnnotation
- // }
- // }
- function createIdentifier(name) {
- return {
- type: 'Identifier',
- value: name,
- optional: false,
- span: {},
- };
- }
- function createFunctionDeclaration(name, func, params) {
- if (!params) {
- if (func.type === 'FunctionExpression') {
- params = func.params;
- }
- else if (func.type === 'ArrowFunctionExpression') {
- params = [];
- func.params.forEach((p) => {
- if (p.type === 'Identifier') {
- params.push({
- type: 'Parameter',
- pat: p,
- span: {},
- });
- }
- });
- }
- }
- return {
- type: 'FunctionDeclaration',
- identifier: createIdentifier(name),
- declare: false,
- params: params,
- generator: false,
- async: func.async,
- typeParameters: func.typeParameters,
- returnType: func.returnType,
- span: {},
- };
- }
|