提交 14278bb9 编写于 作者: fxy060608's avatar fxy060608

wip(uts): compiler

上级 0d299c60
......@@ -17,4 +17,5 @@ packages/uni-mp-toutiao/lib
packages/uni-mp-vue/lib
packages/uni-mp-weixin/lib
packages/uni-mp-quickapp-webview/lib
packages/vite-plugin-uni/lib
\ No newline at end of file
packages/vite-plugin-uni/lib
packages/uni-uts-vite/lib
\ No newline at end of file
......@@ -6,7 +6,7 @@
"output": {
"format": "cjs"
},
"external": ["@dcloudio/uni-app-vite"]
"external": ["@dcloudio/uni-app-vite", "@dcloudio/uni-uts-vite"]
},
{
"input": {
......
'use strict';
var uniAppVite = require('@dcloudio/uni-app-vite');
var appVite = require('@dcloudio/uni-app-vite');
var utsVite = require('@dcloudio/uni-uts-vite');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var uniAppVite__default = /*#__PURE__*/_interopDefaultLegacy(uniAppVite);
var appVite__default = /*#__PURE__*/_interopDefaultLegacy(appVite);
var utsVite__default = /*#__PURE__*/_interopDefaultLegacy(utsVite);
var index = [appVite__default["default"], utsVite__default["default"]];
module.exports = uniAppVite__default["default"];
module.exports = index;
export { default } from '@dcloudio/uni-app-vite'
import appVite from '@dcloudio/uni-app-vite'
import utsVite from '@dcloudio/uni-uts-vite'
export default [appVite, utsVite]
......@@ -386,8 +386,21 @@ function createNativeEvent(evt, htmlElement = false) {
event.touches = evt.touches;
event.changedTouches = evt.changedTouches;
}
{
wrapperEvent(event, evt);
}
return event;
}
function wrapperEvent(event, evt) {
shared.extend(event, {
preventDefault() {
return evt.preventDefault();
},
stopPropagation() {
return evt.stopPropagation();
}
});
}
const invokeOnCallback = (name, res) => UniServiceJSBridge.emit("api." + name, res);
let invokeViewMethodId = 1;
function publishViewMethodName() {
......@@ -1644,15 +1657,10 @@ function resolveColor(color) {
color[3] = color[3] / 255;
return "rgba(" + color.join(",") + ")";
}
function processTouches(target, touches) {
const eventTarget = target;
let boundingClientRect = eventTarget.getBoundingClientRect();
return Array.from(touches).map((touch) => {
return {
identifier: touch.identifier,
x: touch.clientX - boundingClientRect.left,
y: touch.clientY - boundingClientRect.top
};
function processTouches(rect, touches) {
Array.from(touches).forEach((touch) => {
touch.x = touch.clientX - rect.left;
touch.y = touch.clientY - rect.top;
});
}
let tempCanvas;
......@@ -1755,16 +1763,10 @@ function useListeners(props2, Listeners, trigger) {
let eventHandler = [];
if (existing) {
eventHandler.push(withWebEvent(($event) => {
trigger(event.replace("on", "").toLocaleLowerCase(), shared.extend({}, (() => {
let obj = {};
for (const key in $event) {
obj[key] = $event[key];
}
return obj;
})(), {
touches: processTouches($event.currentTarget, $event.touches),
changedTouches: processTouches($event.currentTarget, $event.changedTouches)
}));
const rect = $event.currentTarget.getBoundingClientRect();
processTouches(rect, $event.touches);
processTouches(rect, $event.changedTouches);
trigger(event.replace("on", "").toLocaleLowerCase(), $event);
}));
}
if (props2.disableScroll && event === "onTouchmove") {
......
......@@ -1271,7 +1271,6 @@ function $nne(evt, eventValue, instance2) {
res.changedTouches = normalizeTouchEvent(evt.changedTouches, top);
}
{
wrapperEvent(res, evt);
return wrapperH5WxsEvent(res, eventValue, instance2) || [res];
}
}
......@@ -1297,6 +1296,9 @@ function createNativeEvent(evt, htmlElement = false) {
event.touches = evt.touches;
event.changedTouches = evt.changedTouches;
}
{
wrapperEvent(event, evt);
}
return event;
}
function wrapperEvent(event, evt) {
......@@ -6559,15 +6561,10 @@ function resolveColor(color) {
color[3] = color[3] / 255;
return "rgba(" + color.join(",") + ")";
}
function processTouches(target, touches) {
const eventTarget = target;
let boundingClientRect = eventTarget.getBoundingClientRect();
return Array.from(touches).map((touch) => {
return {
identifier: touch.identifier,
x: touch.clientX - boundingClientRect.left,
y: touch.clientY - boundingClientRect.top
};
function processTouches(rect, touches) {
Array.from(touches).forEach((touch) => {
touch.x = touch.clientX - rect.left;
touch.y = touch.clientY - rect.top;
});
}
let tempCanvas;
......@@ -6673,16 +6670,10 @@ function useListeners(props2, Listeners, trigger) {
let eventHandler = [];
if (existing) {
eventHandler.push(withWebEvent(($event) => {
trigger(event.replace("on", "").toLocaleLowerCase(), extend({}, (() => {
let obj = {};
for (const key in $event) {
obj[key] = $event[key];
}
return obj;
})(), {
touches: processTouches($event.currentTarget, $event.touches),
changedTouches: processTouches($event.currentTarget, $event.changedTouches)
}));
const rect = $event.currentTarget.getBoundingClientRect();
processTouches(rect, $event.touches);
processTouches(rect, $event.changedTouches);
trigger(event.replace("on", "").toLocaleLowerCase(), $event);
}));
}
if (props2.disableScroll && event === "onTouchmove") {
......
const moduleName = '__MODULE_NAME__'
const moduleDefine = '__MODULE_DEFINE__'
var module = initModule(moduleDefine)
let callbackId = 1
const objectToString = Object.prototype.toString
const toTypeString = (value) => objectToString.call(value)
const isPlainObject = (val) => toTypeString(val) === '[object Object]'
const callbacks = {}
function normalizeArg(arg) {
if (typeof arg === 'function') {
const id = callbackId++
callbacks[id] = arg
return id
} else if (isPlainObject(arg)) {
Object.keys(arg).forEach((name) => {
arg[name] = normalizeArg(arg[name])
})
}
return arg
}
function isProxyInvokeCallbackResponse(res) {
return !!res.name
}
function moduleGetter(proxy, module, method, defines) {
const invokeCallback = ({ id, name, params, keepAlive }) => {
const callback = callbacks[id]
if (callback) {
callback(...params)
if (!keepAlive) {
delete callbacks[id]
}
} else {
console.error(`${module}.${method} ${name} is not found`)
}
}
return (...args) => {
const params = args.map((arg) => normalizeArg(arg))
const invokeArgs = { module, method, params, async: !!defines.async }
if (defines.async) {
return new Promise((resolve, reject) => {
proxy.invoke(invokeArgs, (res) => {
if (isProxyInvokeCallbackResponse(res)) {
invokeCallback(res)
} else {
if (res.errMsg) {
reject(res.errMsg)
} else {
resolve(res.params)
}
}
})
})
}
return proxy.invoke(invokeArgs, invokeCallback)
}
}
function initModule(moduleDefine) {
let proxy
const moduleProxy = {}
for (const methodName in moduleDefine) {
Object.defineProperty(moduleProxy, methodName, {
enumerable: true,
configurable: true,
get: () => {
if (!proxy) {
proxy = uni.requireNativePlugin('proxy-module')
}
return moduleGetter(
proxy,
moduleName,
methodName,
moduleDefine[methodName]
)
},
})
}
const moduleName = '__MODULE_NAME__';
const moduleDefine = '__MODULE_DEFINE__';
var module = initModule(moduleDefine);
let callbackId = 1;
const objectToString = Object.prototype.toString;
const toTypeString = (value) => objectToString.call(value);
const isPlainObject = (val) => toTypeString(val) === '[object Object]';
const callbacks = {};
function normalizeArg(arg) {
if (typeof arg === 'function') {
const id = callbackId++;
callbacks[id] = arg;
return id;
}
else if (isPlainObject(arg)) {
Object.keys(arg).forEach((name) => {
;
arg[name] = normalizeArg(arg[name]);
});
}
return arg;
}
function isProxyInvokeCallbackResponse(res) {
return !!res.name;
}
function moduleGetter(proxy, module, method, defines) {
const invokeCallback = ({ id, name, params, keepAlive, }) => {
const callback = callbacks[id];
if (callback) {
callback(...params);
if (!keepAlive) {
delete callbacks[id];
}
}
else {
console.error(`${module}.${method} ${name} is not found`);
}
};
return (...args) => {
const params = args.map((arg) => normalizeArg(arg));
const invokeArgs = { module, method, params, async: !!defines.async };
if (defines.async) {
return new Promise((resolve, reject) => {
proxy.invoke(invokeArgs, (res) => {
if (isProxyInvokeCallbackResponse(res)) {
invokeCallback(res);
}
else {
if (res.errMsg) {
reject(res.errMsg);
}
else {
resolve(res.params);
}
}
});
});
}
return proxy.invoke(invokeArgs, invokeCallback);
};
}
function initModule(moduleDefine) {
let proxy;
const moduleProxy = {};
for (const methodName in moduleDefine) {
Object.defineProperty(moduleProxy, methodName, {
enumerable: true,
configurable: true,
get: () => {
if (!proxy) {
proxy = uni.requireNativePlugin('proxy-module');
}
return moduleGetter(proxy, moduleName, methodName, moduleDefine[methodName]);
},
});
}
return moduleProxy;
}
export { module as default, normalizeArg }
export { module as default, normalizeArg };
......@@ -119,4 +119,5 @@ function initModule(moduleDefine: Record<string, ModuleMethodDefine>) {
},
})
}
return moduleProxy
}
import type { Plugin } from 'vite'
import fs from 'fs'
import path from 'path'
import { parseJson, parseVueRequest } from '@dcloudio/uni-cli-shared'
import { normalizePath, parseVueRequest } from '@dcloudio/uni-cli-shared'
import {
ExportDefaultDeclaration,
Module,
TsFunctionType,
TsType,
TsTypeAnnotation,
} from '../../types/types'
// 需要区分 android,iOS
......@@ -15,40 +17,22 @@ export function uniUtsV1Plugin(): Plugin {
name: 'uni:uts-v1',
apply: 'build',
enforce: 'pre',
resolveId(id) {
if (!id.includes('uni_modules')) {
return
}
const pkgPath = path.join(id, 'package.json')
if (!fs.existsSync(pkgPath)) {
return
}
const pkg = parseJson(fs.readFileSync(pkgPath, 'utf-8'))
if (pkg.uni_modules?.type !== 'uts') {
return
}
return (
path.join(id, pkg.main || 'interface.uts') +
'?module=' +
path.basename(path.dirname(pkgPath))
)
},
transform(code, id, opts) {
async transform(code, id, opts) {
if (opts && opts.ssr) {
return
}
const { filename, query } = parseVueRequest(id)
const { filename } = parseVueRequest(id)
if (path.extname(filename) !== '.uts') {
return
}
const moduleName = (query as any).module as string
const moduleName = parseModuleId(filename)
if (!moduleName) {
return
}
// 懒加载 uts
// eslint-disable-next-line no-restricted-globals
const { parse } = require('@dcloudio/uts')
const ast = parse(code)
const ast = await parse(code)
if (!moduleCode) {
moduleCode = fs.readFileSync(
path.resolve(__dirname, '../../lib/module.js'),
......@@ -62,6 +46,15 @@ export function uniUtsV1Plugin(): Plugin {
}
}
function parseModuleId(filepath: string) {
const parts = normalizePath(filepath).split('/')
const index = parts.findIndex((part) => part === 'uni_modules')
if (index > -1) {
return parts[index + 1]
}
return ''
}
function parseModuleDefines(ast: Module) {
const module: Record<string, { async: boolean }> = {}
const defaultDecl = ast.body.find(
......@@ -72,17 +65,39 @@ function parseModuleDefines(ast: Module) {
}
const body = defaultDecl.decl.body.body
body.forEach((item) => {
if (item.type !== 'TsMethodSignature' || item.key.type !== 'Identifier') {
return
}
const methodName = item.key.value
module[methodName] = {
async: item.typeAnn ? isReturnPromise(item.typeAnn) : false,
if (item.type === 'TsPropertySignature') {
const { key, typeAnnotation } = item
if (key.type !== 'Identifier') {
return
}
if (!typeAnnotation) {
return
}
const functionType = typeAnnotation.typeAnnotation
if (!isFunctionType(functionType)) {
return
}
const methodName = key.value
module[methodName] = {
async: isReturnPromise(functionType.typeAnnotation),
}
} else if (item.type === 'TsMethodSignature') {
if (item.key.type !== 'Identifier') {
return
}
const methodName = item.key.value
module[methodName] = {
async: item.typeAnn ? isReturnPromise(item.typeAnn) : false,
}
}
})
return module
}
function isFunctionType(type: TsType): type is TsFunctionType {
return type.type === 'TsFunctionType'
}
function isReturnPromise({ typeAnnotation }: TsTypeAnnotation) {
return (
typeAnnotation.type === 'TsTypeReference' &&
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册