初始化fy

This commit is contained in:
yziiy
2025-08-11 11:51:38 +08:00
parent 98ce20e897
commit 7e21160e13
19770 changed files with 3108698 additions and 0 deletions

View File

@@ -0,0 +1,13 @@
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
insert_final_newline = false

View File

@@ -0,0 +1,2 @@
/// <reference path="../lib/HBuilderX.d.ts" />
/// <reference path="./plus.d.ts" />

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,2 @@
/// <reference path="./uni-app/index.d.ts" />
/// <reference path="./html5plus/plus.d.ts" />

View File

@@ -0,0 +1,61 @@
declare namespace HBuilderX {
interface AttrString extends String {}
interface AttrValueString extends String {}
interface ClassString extends String {}
interface IDString extends String {}
interface HTMLEventString extends String {}
interface HTMLElementProperties extends String {}
interface HTMLStyleObjectString extends String {}
interface cssPropertyString extends String {}
interface cssPropertyValueString extends String {}
interface cssSelectorString extends String {}
interface ColorString extends String {}
interface ParentField extends String {}
interface RequireCommonString extends String {}
interface ValidateFunctionString extends String {}
interface VueI18NKeyString extends String {}
interface SchemaField extends String {}
interface URIString extends String {}
interface CSSURIString extends String {}
interface JSURIString extends String {}
interface HTMLURIString extends String {}
interface ImageURIString extends String {}
interface PageURIString extends String {}
interface NPageURIString extends String {}
interface CssImportURIString extends String {}
interface ScssImportURIString extends String {}
interface LessImportURIString extends String {}
interface ImportURIString extends String {}
interface FontURIString extends String {}
interface AudioURIString extends String {}
interface VideoURIString extends String {}
interface VueURIString extends String {}
interface MarkdownURIString extends String {}
interface ClientDBActionString extends String {}
interface CloudFunctions extends String {}
interface CloudObjects extends String {}
interface DBCollectionString extends String {}
interface DBFieldOrderByString extends String {}
interface DBFieldString extends String {}
interface JQLString extends String {}
interface ModuleURIString extends String {}
interface CharsetString extends String {}
interface CSSString extends String {}
interface EventString extends String {}
interface FontString extends String {}
interface HTMLString extends String {}
interface LengthString extends String {}
interface ModuleString extends String {}
interface MultimediaString extends String {}
interface SqlString extends String {}
interface TagString extends String {}
interface TimeString extends String {}
interface TypeString extends String {}
interface ValueString extends String {}
interface VuexMutationMethods extends String {}
interface UniLivePlayerURIString extends String {}
interface VueDataString extends String {}
interface VueEventString extends String {}
interface VuexDispatchString extends String {}
interface VuexCommitString extends String {}
}

View File

@@ -0,0 +1,25 @@
{
"name": "@dcloudio/types",
"version": "3.3.2",
"description": "uni-app types",
"typings": "index.d.ts",
"scripts": {
"tslint": "tslint --project ./ --fix",
"dtslint": "dtslint ./",
"test": "dtslint ./",
"build:wx": "node ./scripts/build-wx.js",
"build": "npm run build:wx && npm run build:promisify",
"prepublishOnly": "npm run test",
"build:promisify": "node ./scripts/build-promisify.js"
},
"author": "fxy060608",
"license": "Apache-2.0",
"devDependencies": {
"@definitelytyped/dtslint": "^0.0.115",
"miniprogram-api-typings": "3.7.1",
"ts-morph": "^17.0.1",
"tslint": "^5.14.0",
"typescript": "^4.7.4",
"vue": "2.6"
}
}

View File

@@ -0,0 +1,218 @@
declare namespace App {
interface ReferrerInfo {
/**
* 来源小程序或公众号或App的 appId
*
* 以下场景支持返回 referrerInfo.appId
* - 1020公众号 profile 页相关小程序列表): appId
* - 1035公众号自定义菜单来源公众号 appId
* - 1036App 分享消息卡片):来源应用 appId
* - 1037小程序打开小程序来源小程序 appId
* - 1038从另一个小程序返回来源小程序 appId
* - 1043公众号模板消息来源公众号 appId
*/
appId: string;
/**
* 来源小程序传过来的数据scene=1037或1038时支持
*/
extraData?: any;
}
interface LaunchShowOption {
/**
* 打开小程序的路径
*/
path: string;
/**
* 打开小程序的query
*/
query: AnyObject;
/**
* 打开小程序的场景值
* - 1001: 发现栏小程序主入口「最近使用」列表基础库2.2.4版本起包含「我的小程序」列表)
* - 1005: 顶部搜索框的搜索结果页
* - 1006: 发现栏小程序主入口搜索框的搜索结果页
* - 1007: 单人聊天会话中的小程序消息卡片
* - 1008: 群聊会话中的小程序消息卡片
* - 1011: 扫描二维码
* - 1012: 长按图片识别二维码
* - 1013: 手机相册选取二维码
* - 1014: 小程序模板消息
* - 1017: 前往体验版的入口页
* - 1019: 微信钱包
* - 1020: 公众号 profile 页相关小程序列表
* - 1022: 聊天顶部置顶小程序入口
* - 1023: 安卓系统桌面图标
* - 1024: 小程序 profile 页
* - 1025: 扫描一维码
* - 1026: 附近小程序列表
* - 1027: 顶部搜索框搜索结果页「使用过的小程序」列表
* - 1028: 我的卡包
* - 1029: 卡券详情页
* - 1030: 自动化测试下打开小程序
* - 1031: 长按图片识别一维码
* - 1032: 手机相册选取一维码
* - 1034: 微信支付完成页
* - 1035: 公众号自定义菜单
* - 1036: App 分享消息卡片
* - 1037: 小程序打开小程序
* - 1038: 从另一个小程序返回
* - 1039: 摇电视
* - 1042: 添加好友搜索框的搜索结果页
* - 1043: 公众号模板消息
* - 1044: 带 shareTicket 的小程序消息卡片
* - 1045: 朋友圈广告
* - 1046: 朋友圈广告详情页
* - 1047: 扫描小程序码
* - 1048: 长按图片识别小程序码
* - 1049: 手机相册选取小程序码
* - 1052: 卡券的适用门店列表
* - 1053: 搜一搜的结果页
* - 1054: 顶部搜索框小程序快捷入口
* - 1056: 音乐播放器菜单
* - 1057: 钱包中的银行卡详情页
* - 1058: 公众号文章
* - 1059: 体验版小程序绑定邀请页
* - 1064: 微信连Wi-Fi状态栏
* - 1067: 公众号文章广告
* - 1068: 附近小程序列表广告
* - 1069: 移动应用
* - 1071: 钱包中的银行卡列表页
* - 1072: 二维码收款页面
* - 1073: 客服消息列表下发的小程序消息卡片
* - 1074: 公众号会话下发的小程序消息卡片
* - 1077: 摇周边
* - 1078: 连Wi-Fi成功页
* - 1079: 微信游戏中心
* - 1081: 客服消息下发的文字链
* - 1082: 公众号会话下发的文字链
* - 1084: 朋友圈广告原生页
* - 1089: 微信聊天主界面下拉「最近使用」栏基础库2.2.4版本起包含「我的小程序」栏)
* - 1090: 长按小程序右上角菜单唤出最近使用历史
* - 1091: 公众号文章商品卡片
* - 1092: 城市服务入口
* - 1095: 小程序广告组件
* - 1096: 聊天记录
* - 1097: 微信支付签约页
* - 1099: 页面内嵌插件
* - 1102: 公众号 profile 页服务预览
* - 1103: 发现栏小程序主入口「我的小程序」列表基础库2.2.4版本起废弃)
* - 1104: 微信聊天主界面下拉「我的小程序」栏基础库2.2.4版本起废弃)
*/
scene: number;
/**
* 打开小程序的场景值
*/
shareTicket: string;
/**
* 当场景为由从另一个小程序或公众号或App打开时返回此字段
*/
referrerInfo?: ReferrerInfo;
}
interface PageNotFoundOption {
/**
* 不存在页面的路径
*/
path: string;
/**
* 打开不存在页面的 query
*/
query: AnyObject;
/**
* 是否本次启动的首个页面(例如从分享等入口进来,首个页面是开发者配置的分享页面)
*/
isEntryPage: boolean;
}
interface AppInstance<T extends AnyObject = {}> {
/**
* 全局对象
* 文档:[https://uniapp.dcloud.io/collocation/App?id=globaldata](https://uniapp.dcloud.io/collocation/App?id=globaldata)
*/
globalData?: AnyObject;
/**
* 生命周期回调 监听应用初始化
*
* 应用初始化完成时触发,全局只触发一次。
*
* 文档: [https://uniapp.dcloud.io/collocation/frame/lifecycle](https://uniapp.dcloud.io/collocation/frame/lifecycle)
*/
onLaunch?(options?: LaunchShowOption): void;
/**
* 生命周期回调 监听应用显示
*
* 应用启动,或从后台进入前台显示时触发
*
* 文档: [https://uniapp.dcloud.io/collocation/frame/lifecycle](https://uniapp.dcloud.io/collocation/frame/lifecycle)
*/
onShow?(options?: LaunchShowOption): void;
/**
* 生命周期回调 监听应用隐藏
*
* 应用从前台进入后台时触发
*
* 文档: [https://uniapp.dcloud.io/collocation/frame/lifecycle](https://uniapp.dcloud.io/collocation/frame/lifecycle)
*/
onHide?(): void;
/**
* 错误监听函数
* 小程序发生脚本错误或 API 调用报错时触发
* @param error 错误信息,包含堆栈
*
* 文档: [https://uniapp.dcloud.io/collocation/frame/lifecycle](https://uniapp.dcloud.io/collocation/frame/lifecycle)
*/
onError?(error: string): void;
/**
* 页面不存在监听函数
*
* 应用要打开的页面不存在时触发,会带上页面信息回调该函数
*
* **注意:**
* 1. 如果开发者没有添加 `onPageNotFound` 监听,当跳转页面不存在时,将推入微信客户端原生的页面不存在提示页面。
* 2. 如果 `onPageNotFound` 回调中又重定向到另一个不存在的页面,将推入微信客户端原生的页面不存在提示页面,并且不再回调 `onPageNotFound`。
*
* 文档: [https://uniapp.dcloud.io/collocation/frame/lifecycle](https://uniapp.dcloud.io/collocation/frame/lifecycle)
*/
onPageNotFound?(options: PageNotFoundOption): void;
/**
* 未处理的 Promise 拒绝事件监听函数
*
* 文档: [https://uniapp.dcloud.io/collocation/frame/lifecycle](https://uniapp.dcloud.io/collocation/frame/lifecycle)
*/
onUnhandledRejection?(options: UniNamespace.OnUnhandledRejectionCallbackResult): void;
/**
* 监听系统主题变化
*
* 文档: [https://uniapp.dcloud.io/collocation/frame/lifecycle](https://uniapp.dcloud.io/collocation/frame/lifecycle)
*/
onThemeChange?(options: UniNamespace.OnThemeChangeCallbackResult): void;
/**
* 监听 nvue 页面消息
*
* nvue 页面使用 `uni.postMessage` 发送消息时触发
*
* 文档: [https://uniapp.dcloud.io/collocation/frame/lifecycle](https://uniapp.dcloud.io/collocation/frame/lifecycle)
*/
onUniNViewMessage?(options: AnyObject): void;
}
type AppConstructor = <T extends AnyObject & AppInstance>(
options: AppInstance<T> & T,
) => void;
interface GetAppOption {
/**
* 在 `App` 未定义时返回默认实现。当App被调用时默认实现中定义的属性会被覆盖合并到App中。一般用于独立分包
*/
allowDefault: boolean;
}
type GetApp = <T extends AnyObject>(opts?: GetAppOption) => AppInstance<T> & T;
}
declare const getApp: App.GetApp;
declare const createApp: any;
declare const createPage: any;
declare const createComponent: any;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,7 @@
interface AnyObject {
[key: string]: any;
}
type KVInfer<T> = { [K in keyof T]: T[K] };
type Void<T> = T | undefined | null;

View File

@@ -0,0 +1,11 @@
/// <reference path="../lib/HBuilderX.d.ts" />
/// <reference path="../html5plus/plus.d.ts" />
/// <reference path="./common.d.ts" />
/// <reference path="./app.d.ts" />
/// <reference path="./page.d.ts" />
/// <reference path="./uni/index.d.ts" />
/// <reference path="./uni-patches/index.d.ts" />
/// <reference path="./cloud.d.ts" />
import UniApp = UniNamespace;
import UniCloud = UniCloudNamespace;

View File

@@ -0,0 +1,418 @@
declare namespace Page {
interface CustomShareContent {
/**
* 转发标题。默认值:当前应用名称
*/
title?: string;
/**
* 转发路径,必须是以 / 开头的完整路径。默认值:当前页面 path
*/
path?: string;
/**
* 自定义图片路径可以是本地文件路径、代码包文件路径或者网络图片路径。支持PNG及JPG。显示图片长宽比是 5:4默认值使用默认截图
*/
imageUrl?: string;
/**
* 如果该参数存在,则以 resolve 结果为准,如果三秒内不 resolve分享会使用上面传入的默认参数
*/
promise?: Promise<{
/**
* 转发标题。默认值:当前应用名称
*/
title?: string;
/**
* 转发路径,必须是以 / 开头的完整路径。默认值:当前页面 path
*/
path?: string;
/**
* 自定义图片路径可以是本地文件路径、代码包文件路径或者网络图片路径。支持PNG及JPG。显示图片长宽比是 5:4默认值使用默认截图
*/
imageUrl?: string;
}>;
/**
* 自定义分享描述
*/
desc?: string;
/**
* 自定义吱口令文案,最多 28 个字符
*/
content?: string;
/**
* 自定义分享预览大图,建议尺寸 750x825支持网络图片路径、apFilePath 路径、相对路径不支持base64
*/
bgImgUrl?: string;
/**
* 自定义社交图片链接,作为分享到支付宝好友时的主体图片。建议尺寸 376x330
*/
scImgUrl?: string;
/**
* 生成分享截图的搜索引导,设置该参数后,会在分享图片中增加上支付宝搜“设置关键字”的内容,设置关键字不能超过 5 个字
*/
searchTip?: string;
/**
* 分享成功后回调
*/
success?: () => void;
/**
* 分享失败后回调
*/
fail?: () => void;
/**
* 开发者后台设置的分享素材模板 id
*/
templateId?: string;
/**
* PC端打开小程序加载的页面不支持可传空字符串
*/
PCPath?: string;
/**
* PC端打开小程序加载的模式若需要在PC端打开小程序则必须传PCMode字段
*/
PCMode?: string;
/**
* PCQQ、低版本手机QQ无法执行小程序时打开的H5页面
*/
generalWebpageUrl?: string;
/**
* 监听用户点击页面内转发按钮的,只有带上该参数,才支持快速分享
*/
entryDataHash?: string;
/**
* 分享模板id可以使用不同的分享模版可选模版参考管理端分享模版一栏
*/
shareTemplateId?: string;
/**
* 分享模板的数据不同的模板id需要不同的数据数据的格式请参考管理端分享模版一栏
*/
shareTemplateData?: string;
/**
* 指定分享的类型
*/
shareType?: string;
/**
* 转发形式1 - 京东小程序正式版2 - 京东小程序体验版京东App9.0.0开始不填或者其他值都会先判断是否有url参数如果有打开分享后显示url对应页面否则默认生成京东小程序官方的一个分享中间页面点击可跳到京东app里面的对应小程序
*/
type?: string;
/**
* 渠道不写默认微信朋友微信朋友圈可用值有Wxfriends,QQfriends,Wxmoments,QQzone,Sinaweibo
*/
channel?: string;
/**
* h5链接地址h5分享填写不填默认中间页
*/
url?: string;
/**
* 口令分享渠道可用值有Wxfriends,QQfriends,Wxmoments,QQzone,Sinaweibo当需要口令分享时需要配置此选项
*/
keyShareChannel?: string;
/**
* 海报分享本地图片地址海报图片由开发者生成后将图片地址传入jdfile开头的格式
*/
localImageUrl?: string;
/**
* 海报分享网络图片地址海报图片由开发者生成后将图片地址传入注意localImageUrl、onlineImageUrl建议开发者使用时只传一个值 如果传入两个值 优先localImageUrl
*/
onlineImageUrl?: string;
}
interface ShareTimelineContent {
/**
* 自定义标题,即朋友圈列表页上显示的标题。默认值:当前小程序名称
*/
title?: string;
/**
* 自定义页面路径中携带的参数,如 path?a=1&b=2 的 “?” 后面部分。默认值:当前页面路径携带的参数
*/
query?: string;
/**
* 自定义图片路径,可以是本地文件或者网络图片。支持 PNG 及 JPG显示图片长宽比是 1:1。默认值小程序 Logo
*/
imageUrl?: string;
}
interface PageScrollOption {
/**
* 页面在垂直方向已滚动的距离(单位 px
*/
scrollTop: number;
}
interface ResizeOption {
/**
* 页面在垂直方向已滚动的距离(单位 px
*/
scrollTop: number;
/**
* 新的显示区域尺寸
*/
size?: {
/**
* 新的显示区域宽度
*/
windowWidth: number;
/**
* 新的显示区域高度
*/
windowHeight: number;
};
}
interface ShareAppMessageOption {
/**
* 转发事件来源。
* 可选值:
* - `button`:页面内转发按钮;
* - `menu`:右上角转发菜单。
*/
from: "button" | "menu";
/**
* 如果 `from` 值是 `button`,则 `target` 是触发这次转发事件的 `button`,否则为 `undefined`
*/
target: any;
/**
* 页面中包含 `<web-view>` 组件时,返回当前 `<web-view>` 的 url
*/
webViewUrl?: string;
}
interface AddToFavoritesOption {
/**
* 转发事件来源。
* 可选值:
* - `button`:页面内转发按钮;
* - `menu`:右上角转发菜单。
*/
from: "button" | "menu";
/**
* 页面中包含 `<web-view>` 组件时,返回当前 `<web-view>` 的 url
*/
webviewUrl: string;
}
interface CustomFavoritesContent {
/**
* 自定义标题,默认值:页面标题或账号名称
*/
title?: string;
/**
* 自定义 query 字段
*/
path?: string;
/**
* 自定义图片,显示图片长宽比为 11
*/
imageUrl?: string;
}
interface TabItemTapOption {
/**
* 被点击 tabItem 的序号从0开始
*/
index: number;
/**
* 被点击 tabItem 的页面路径
*/
pagePath: string;
/**
* 被点击 tabItem 的按钮文字
*/
text: string;
}
interface NavigationBarButtonTapOption {
/**
* 原生标题栏按钮数组的下标
*/
index: number;
}
interface BackPressOption {
/**
* - backbutton 顶部导航栏左边的返回按钮或 Android 实体返回键
* - navigateBack 返回 API即 uni.navigateBack()
*/
from: 'backbutton' | 'navigateBack';
}
interface NavigationBarSearchInputEvent {
/**
* 搜索输入框输入内容
*/
text: string;
}
interface PageInstanceBaseProps<D extends AnyObject = any> {
/**
* 到当前页面的路径,类型为 `String`
*/
route?: string;
/**
* 获取当前页面的webview对象实例。仅 App 平台支持
*/
$getAppWebview?: () => PlusWebviewWebviewObject;
/**
* 当前页面的 Vue 实例
*/
$vm?: any;
}
interface PageInstance<D extends AnyObject = any, T extends AnyObject = any> extends PageInstanceBaseProps<D> {
/**
* 生命周期回调 监听页面初始化
*
* 页面初始化时触发。一个页面只会调用一次,可以在 onInit 的参数中获取打开当前页面路径中的参数。
* @param query 打开当前页面路径中的参数
*
* 文档: [https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page](https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page)
*/
onInit?(query?: AnyObject): void;
/**
* 生命周期回调 监听页面加载
*
* 页面加载时触发。一个页面只会调用一次,可以在 onLoad 的参数中获取打开当前页面路径中的参数。
* @param query 打开当前页面路径中的参数
*
* 文档: [https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page](https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page)
*/
onLoad?(query?: AnyObject): void;
/**
* 生命周期回调 监听页面显示
*
* 页面显示/切入前台时触发。
*
* 文档: [https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page](https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page)
*/
onShow?(): void;
/**
* 生命周期回调 监听页面初次渲染完成
*
* 页面初次渲染完成时触发。一个页面只会调用一次,代表页面已经准备妥当,可以和视图层进行交互。
*
* 文档: [https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page](https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page)
*/
onReady?(): void;
/**
* 生命周期回调 监听页面隐藏
*
* 页面隐藏/切入后台时触发。 如 `navigateTo` 或底部 `tab` 切换到其他页面,应用切入后台等。
*
* 文档: [https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page](https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page)
*/
onHide?(): void;
/**
* 生命周期回调 监听页面卸载
*
* 页面卸载时触发。如 `redirectTo` 或 `navigateBack` 到其他页面时。
*
* 文档: [https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page](https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page)
*/
onUnload?(): void;
/**
* 监听用户下拉动作
* - 需要在 `pages.json` 的页面配置中开启 `enablePullDownRefresh` 。
* - 可以通过 `uni.startPullDownRefresh` 触发下拉刷新,调用后触发下拉刷新动画,效果与用户手动下拉刷新一致。
* - 当处理完数据刷新后,`uni.stopPullDownRefresh` 可以停止当前页面的下拉刷新。
*
* 文档: [https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page](https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page)
*/
onPullDownRefresh?(): void;
/**
* 页面上拉触底事件的处理函数
* - 可以在 `pages.json` 的页面配置中设置触发距离 `onReachBottomDistance` 。
* - 在触发距离内滑动期间,本事件只会被触发一次。
*
* 文档: [https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page](https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page)
*/
onReachBottom?(): void;
/**
* 用户点击右上角转发
*
* 监听用户点击页面内转发按钮(`<button>` 组件 `open-type="share"`)或右上角菜单“转发”按钮的行为,并自定义转发内容。
* @param options 分享发起来源参数
* @return 转发内容
*
* 文档: [https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page](https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page)
*/
onShareAppMessage?(options: ShareAppMessageOption): CustomShareContent | Promise<Omit<CustomShareContent, "promise">>;
/**
* 用户点击右上角转发到朋友圈
*
* 监听右上角菜单“分享到朋友圈”按钮的行为,并自定义发享内容。
*
* 文档: [https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page](https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page)
*/
onShareTimeline?(): ShareTimelineContent;
/**
* 用户点击右上角收藏
*
* 监听用户点击右上角菜单“收藏”按钮的行为,并自定义收藏内容。
*
* 文档: [https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page](https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page)
*/
onAddToFavorites?(options: AddToFavoritesOption): CustomFavoritesContent;
/**
* 页面滚动触发事件的处理函数
*
* 监听用户滑动页面事件。
* @param options 页面滚动参数
*
* 文档: [https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page](https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page)
*/
onPageScroll?(options: PageScrollOption): void;
/**
* 页面尺寸改变时触发
* @param options 页面滚动参数
*
* 文档: [https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page](https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page)
*/
onResize?(options: ResizeOption): void;
/**
* 当前是 tab 页时,点击 tab 时触发
* @param options tab 点击参数
*
* 文档: [https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page](https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page)
*/
onTabItemTap?(options: TabItemTapOption): void;
/**
* 监听原生标题栏按钮点击事件
* @param options tab 点击参数
*
* 文档: [https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page](https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page)
*/
onNavigationBarButtonTap?(options: NavigationBarButtonTapOption): void;
/**
* 监听页面返回
* @param options tab 点击参数
* @return 返回 `true` 时阻止页面返回
*
* 文档: [https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page](https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page)
*/
onBackPress?(options: BackPressOption): any;
/**
* 监听原生标题栏搜索输入框输入内容变化事件
*
* 文档: [https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page](https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page)
*/
onNavigationBarSearchInputChanged?(event: NavigationBarSearchInputEvent): void;
/**
* 监听原生标题栏搜索输入框搜索事件,用户点击软键盘上的“搜索”按钮时触发。
*
* 文档: [https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page](https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page)
*/
onNavigationBarSearchInputConfirmed?(event: NavigationBarSearchInputEvent): void;
/**
* 监听原生标题栏搜索输入框点击事件
*
* 文档: [https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page](https://uniapp.dcloud.io/collocation/frame/lifecycle?id=page)
*/
onNavigationBarSearchInputClicked?(): void;
}
type PageConstructor = <T extends AnyObject & PageInstance>(
options: PageInstance<AnyObject, T> & T,
) => void;
type GetCurrentPages = <T extends AnyObject = {}>() => Array<PageInstance<AnyObject, T> & T>;
}
declare const getCurrentPages: Page.GetCurrentPages;

View File

@@ -0,0 +1,2 @@
/// <reference path="./wx/index.d.ts" />
/// <reference path="./promisify/index.d.ts" />

View File

@@ -0,0 +1,34 @@
declare namespace UniNamespace {
type PromisifySuccessResult<
P,
T extends {
success?: (...args: any[]) => void
},
R = void
> = P extends {
success: any
}
? R
: P extends { fail: any }
? R
: P extends { complete: any }
? R
: Promise<Parameters<Exclude<T['success'], undefined>>[0]>;
type ErrorFirstArray<T> = [any, T];
type PromisifySuccessResultLegacy<
P,
T extends {
success?: (...args: any[]) => void
}
> = P extends {
success: any
}
? void
: P extends { fail: any }
? void
: P extends { complete: any }
? void
: Promise<ErrorFirstArray<Parameters<Exclude<T['success'], undefined>>[0]>>;
}

View File

@@ -0,0 +1,2 @@
/// <reference path="./common.d.ts" />
/// <reference path="./uni.d.ts" />

View File

@@ -0,0 +1,139 @@
interface Uni {
getSystemInfo<T extends UniNamespace.GetSystemInfoOptions = UniNamespace.GetSystemInfoOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.GetSystemInfoOptions>;
getImageInfo<T extends UniNamespace.GetImageInfoOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.GetImageInfoOptions>;
getBatteryInfo<T extends UniNamespace.GetBatteryInfoOption = UniNamespace.GetBatteryInfoOption>(option?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.GetBatteryInfoOption>;
startWifi<T extends UniNamespace.StartWifiOption = UniNamespace.StartWifiOption>(option?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.StartWifiOption>;
stopWifi<T extends UniNamespace.StopWifiOption = UniNamespace.StopWifiOption>(option?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.StopWifiOption>;
connectWifi<T extends UniNamespace.ConnectWifiOption = UniNamespace.ConnectWifiOption>(option: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.ConnectWifiOption>;
getConnectedWifi<T extends UniNamespace.GetConnectedWifiOption = UniNamespace.GetConnectedWifiOption>(option?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.GetConnectedWifiOption>;
getWifiList<T extends UniNamespace.GetWifiListOption = UniNamespace.GetWifiListOption>(option?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.GetWifiListOption>;
configMTLS<T extends UniNamespace.ConfigMTLSOptions = UniNamespace.ConfigMTLSOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.ConfigMTLSOptions>;
sendSocketMessage<T extends UniNamespace.SendSocketMessageOptions = UniNamespace.SendSocketMessageOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.SendSocketMessageOptions>;
closeSocket<T extends UniNamespace.CloseSocketOptions = UniNamespace.CloseSocketOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.CloseSocketOptions>;
chooseImage<T extends UniNamespace.ChooseImageOptions = UniNamespace.ChooseImageOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.ChooseImageOptions>;
chooseFile<T extends UniNamespace.ChooseFileOptions = UniNamespace.ChooseFileOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.ChooseFileOptions>;
previewImage<T extends UniNamespace.PreviewImageOptions = UniNamespace.PreviewImageOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.PreviewImageOptions>;
closePreviewImage<T extends UniNamespace.CallBackOptions = UniNamespace.CallBackOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.CallBackOptions>;
saveImageToPhotosAlbum<T extends UniNamespace.SaveImageToPhotosAlbumOptions = UniNamespace.SaveImageToPhotosAlbumOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.SaveImageToPhotosAlbumOptions>;
compressImage<T extends UniNamespace.CompressImageOptions = UniNamespace.CompressImageOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.CompressImageOptions>;
chooseVideo<T extends UniNamespace.ChooseVideoOptions = UniNamespace.ChooseVideoOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.ChooseVideoOptions>;
compressVideo<T extends UniNamespace.CompressVideoOptions = UniNamespace.CompressVideoOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.CompressVideoOptions>;
getVideoInfo<T extends UniNamespace.GetVideoInfoOptions = UniNamespace.GetVideoInfoOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.GetVideoInfoOptions>;
openVideoEditor<T extends UniNamespace.OpenVideoEditorOptions = UniNamespace.OpenVideoEditorOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.OpenVideoEditorOptions>;
saveVideoToPhotosAlbum<T extends UniNamespace.SaveVideoToPhotosAlbumOptions = UniNamespace.SaveVideoToPhotosAlbumOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.SaveVideoToPhotosAlbumOptions>;
saveFile<T extends UniNamespace.SaveFileOptions = UniNamespace.SaveFileOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.SaveFileOptions>;
getFileInfo<T extends UniNamespace.GetFileInfoOptions = UniNamespace.GetFileInfoOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.GetFileInfoOptions>;
getSavedFileList<T extends UniNamespace.GetSavedFileListOptions = UniNamespace.GetSavedFileListOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.GetSavedFileListOptions>;
getSavedFileInfo<T extends UniNamespace.GetSavedFileInfoOptions = UniNamespace.GetSavedFileInfoOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.GetSavedFileInfoOptions>;
removeSavedFile<T extends UniNamespace.RemoveSavedFileOptions = UniNamespace.RemoveSavedFileOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.RemoveSavedFileOptions>;
openDocument<T extends UniNamespace.OpenDocumentOptions = UniNamespace.OpenDocumentOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.OpenDocumentOptions>;
setStorage<T extends UniNamespace.SetStorageOptions = UniNamespace.SetStorageOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.SetStorageOptions>;
getStorage<T extends UniNamespace.GetStorageOptions = UniNamespace.GetStorageOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.GetStorageOptions>;
getStorageInfo<T extends UniNamespace.GetStorageInfoOptions = UniNamespace.GetStorageInfoOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.GetStorageInfoOptions>;
removeStorage<T extends UniNamespace.RemoveStorageOptions = UniNamespace.RemoveStorageOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.RemoveStorageOptions>;
getLocation<T extends UniNamespace.GetLocationOptions = UniNamespace.GetLocationOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.GetLocationOptions>;
chooseLocation<T extends UniNamespace.ChooseLocationOptions = UniNamespace.ChooseLocationOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.ChooseLocationOptions>;
openLocation<T extends UniNamespace.OpenLocationOptions = UniNamespace.OpenLocationOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.OpenLocationOptions>;
getNetworkType<T extends UniNamespace.GetNetworkTypeOptions = UniNamespace.GetNetworkTypeOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.GetNetworkTypeOptions>;
startAccelerometer<T extends UniNamespace.StartAccelerometerOptions = UniNamespace.StartAccelerometerOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.StartAccelerometerOptions>;
stopAccelerometer<T extends UniNamespace.StopAccelerometerOptions = UniNamespace.StopAccelerometerOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.StopAccelerometerOptions>;
startCompass<T extends UniNamespace.StartCompassOptions = UniNamespace.StartCompassOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.StartCompassOptions>;
stopCompass<T extends UniNamespace.StopCompassOptions = UniNamespace.StopCompassOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.StopCompassOptions>;
makePhoneCall<T extends UniNamespace.MakePhoneCallOptions = UniNamespace.MakePhoneCallOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.MakePhoneCallOptions>;
scanCode<T extends UniNamespace.ScanCodeOptions = UniNamespace.ScanCodeOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.ScanCodeOptions>;
setClipboardData<T extends UniNamespace.SetClipboardDataOptions = UniNamespace.SetClipboardDataOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.SetClipboardDataOptions>;
getClipboardData<T extends UniNamespace.GetClipboardDataOptions = UniNamespace.GetClipboardDataOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.GetClipboardDataOptions>;
openAppAuthorizeSetting<T extends UniNamespace.CallBackOptions = UniNamespace.CallBackOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.CallBackOptions>;
getSelectedTextRange<T extends UniNamespace.GetSelectedTextRangeOptions = UniNamespace.GetSelectedTextRangeOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.GetSelectedTextRangeOptions>;
setScreenBrightness<T extends UniNamespace.SetScreenBrightnessOptions = UniNamespace.SetScreenBrightnessOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.SetScreenBrightnessOptions>;
getScreenBrightness<T extends UniNamespace.GetScreenBrightnessOptions = UniNamespace.GetScreenBrightnessOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.GetScreenBrightnessOptions>;
setKeepScreenOn<T extends UniNamespace.SetKeepScreenOnOptions = UniNamespace.SetKeepScreenOnOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.SetKeepScreenOnOptions>;
vibrate<T extends UniNamespace.VibrateOptions = UniNamespace.VibrateOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.VibrateOptions>;
vibrateLong<T extends UniNamespace.VibrateLongOptions = UniNamespace.VibrateLongOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.VibrateLongOptions>;
vibrateShort<T extends UniNamespace.VibrateShortOptions = UniNamespace.VibrateShortOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.VibrateShortOptions>;
addPhoneContact<T extends UniNamespace.AddPhoneContactOptions = UniNamespace.AddPhoneContactOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.AddPhoneContactOptions>;
getBeacons<T extends UniNamespace.GetBeaconsOptions = UniNamespace.GetBeaconsOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.GetBeaconsOptions>;
startBeaconDiscovery<T extends UniNamespace.StartBeaconDiscoveryOptions = UniNamespace.StartBeaconDiscoveryOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.StartBeaconDiscoveryOptions>;
stopBeaconDiscovery<T extends UniNamespace.StopBeaconDiscoveryOptions = UniNamespace.StopBeaconDiscoveryOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.StopBeaconDiscoveryOptions>;
closeBluetoothAdapter<T extends UniNamespace.CloseBluetoothAdapterOptions = UniNamespace.CloseBluetoothAdapterOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.CloseBluetoothAdapterOptions>;
getBluetoothAdapterState<T extends UniNamespace.GetBluetoothAdapterStateOptions = UniNamespace.GetBluetoothAdapterStateOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.GetBluetoothAdapterStateOptions>;
getBluetoothDevices<T extends UniNamespace.GetBluetoothDevicesOptions = UniNamespace.GetBluetoothDevicesOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.GetBluetoothDevicesOptions>;
getConnectedBluetoothDevices<T extends UniNamespace.GetConnectedBluetoothDevicesOptions = UniNamespace.GetConnectedBluetoothDevicesOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.GetConnectedBluetoothDevicesOptions>;
openBluetoothAdapter<T extends UniNamespace.OpenBluetoothAdapterOptions = UniNamespace.OpenBluetoothAdapterOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.OpenBluetoothAdapterOptions>;
startBluetoothDevicesDiscovery<T extends UniNamespace.StartBluetoothDevicesDiscoveryOptions = UniNamespace.StartBluetoothDevicesDiscoveryOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.StartBluetoothDevicesDiscoveryOptions>;
stopBluetoothDevicesDiscovery<T extends UniNamespace.StopBluetoothDevicesDiscoveryOptions = UniNamespace.StopBluetoothDevicesDiscoveryOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.StopBluetoothDevicesDiscoveryOptions>;
closeBLEConnection<T extends UniNamespace.CloseBLEConnectionOptions = UniNamespace.CloseBLEConnectionOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.CloseBLEConnectionOptions>;
createBLEConnection<T extends UniNamespace.CreateBLEConnectionOptions = UniNamespace.CreateBLEConnectionOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.CreateBLEConnectionOptions>;
getBLEDeviceCharacteristics<T extends UniNamespace.GetBLEDeviceCharacteristicsOptions = UniNamespace.GetBLEDeviceCharacteristicsOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.GetBLEDeviceCharacteristicsOptions>;
getBLEDeviceServices<T extends UniNamespace.GetBLEDeviceServicesOptions = UniNamespace.GetBLEDeviceServicesOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.GetBLEDeviceServicesOptions>;
notifyBLECharacteristicValueChange<T extends UniNamespace.NotifyBLECharacteristicValueChangeOptions = UniNamespace.NotifyBLECharacteristicValueChangeOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.NotifyBLECharacteristicValueChangeOptions>;
readBLECharacteristicValue<T extends UniNamespace.ReadBLECharacteristicValueOptions = UniNamespace.ReadBLECharacteristicValueOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.ReadBLECharacteristicValueOptions>;
writeBLECharacteristicValue<T extends UniNamespace.WriteBLECharacteristicValueOptions = UniNamespace.WriteBLECharacteristicValueOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.WriteBLECharacteristicValueOptions>;
setBLEMTU<T extends UniNamespace.SetBLEMTUOptions = UniNamespace.SetBLEMTUOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.SetBLEMTUOptions>;
getBLEDeviceRSSI<T extends UniNamespace.GetBLEDeviceRSSIOptions = UniNamespace.GetBLEDeviceRSSIOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.GetBLEDeviceRSSIOptions>;
showToast<T extends UniNamespace.ShowToastOptions = UniNamespace.ShowToastOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.ShowToastOptions>;
showLoading<T extends UniNamespace.ShowLoadingOptions = UniNamespace.ShowLoadingOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.ShowLoadingOptions>;
showModal<T extends UniNamespace.ShowModalOptions = UniNamespace.ShowModalOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.ShowModalOptions>;
showActionSheet<T extends UniNamespace.ShowActionSheetOptions = UniNamespace.ShowActionSheetOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.ShowActionSheetOptions>;
setNavigationBarTitle<T extends UniNamespace.SetNavigationBarTitleOptions = UniNamespace.SetNavigationBarTitleOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.SetNavigationBarTitleOptions>;
setNavigationBarColor<T extends UniNamespace.SetNavigationbarColorOptions = UniNamespace.SetNavigationbarColorOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.SetNavigationbarColorOptions>;
setTabBarItem<T extends UniNamespace.SetTabBarItemOptions = UniNamespace.SetTabBarItemOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.SetTabBarItemOptions>;
setTabBarStyle<T extends UniNamespace.SetTabBarStyleOptions = UniNamespace.SetTabBarStyleOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.SetTabBarStyleOptions>;
hideTabBar<T extends UniNamespace.HideTabBarOptions = UniNamespace.HideTabBarOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.HideTabBarOptions>;
showTabBar<T extends UniNamespace.ShowTabBarOptions = UniNamespace.ShowTabBarOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.ShowTabBarOptions>;
setTabBarBadge<T extends UniNamespace.SetTabBarBadgeOptions = UniNamespace.SetTabBarBadgeOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.SetTabBarBadgeOptions>;
removeTabBarBadge<T extends UniNamespace.RemoveTabBarBadgeOptions = UniNamespace.RemoveTabBarBadgeOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.RemoveTabBarBadgeOptions>;
showTabBarRedDot<T extends UniNamespace.ShowTabBarRedDotOptions = UniNamespace.ShowTabBarRedDotOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.ShowTabBarRedDotOptions>;
hideTabBarRedDot<T extends UniNamespace.HideTabBarRedDotOptions = UniNamespace.HideTabBarRedDotOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.HideTabBarRedDotOptions>;
navigateTo<T extends UniNamespace.NavigateToOptions = UniNamespace.NavigateToOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.NavigateToOptions>;
redirectTo<T extends UniNamespace.RedirectToOptions = UniNamespace.RedirectToOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.RedirectToOptions>;
reLaunch<T extends UniNamespace.ReLaunchOptions = UniNamespace.ReLaunchOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.ReLaunchOptions>;
switchTab<T extends UniNamespace.SwitchTabOptions = UniNamespace.SwitchTabOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.SwitchTabOptions>;
navigateBack<T extends UniNamespace.NavigateBackOptions = UniNamespace.NavigateBackOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.NavigateBackOptions>;
preloadPage<T extends UniNamespace.PreloadPageOptions = UniNamespace.PreloadPageOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.PreloadPageOptions>;
pageScrollTo<T extends UniNamespace.PageScrollToOptions = UniNamespace.PageScrollToOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.PageScrollToOptions>;
startPullDownRefresh<T extends UniNamespace.StartPullDownRefreshOptions = UniNamespace.StartPullDownRefreshOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.StartPullDownRefreshOptions>;
canvasToTempFilePath<T extends UniNamespace.CanvasToTempFilePathOptions = UniNamespace.CanvasToTempFilePathOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.CanvasToTempFilePathOptions>;
canvasGetImageData<T extends UniNamespace.CanvasGetImageDataOptions = UniNamespace.CanvasGetImageDataOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.CanvasGetImageDataOptions>;
canvasPutImageData<T extends UniNamespace.CanvasPutImageDataOptions = UniNamespace.CanvasPutImageDataOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.CanvasPutImageDataOptions>;
showTopWindow<T extends UniNamespace.CommonOptions = UniNamespace.CommonOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.CommonOptions>;
hideTopWindow<T extends UniNamespace.CommonOptions = UniNamespace.CommonOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.CommonOptions>;
showLeftWindow<T extends UniNamespace.CommonOptions = UniNamespace.CommonOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.CommonOptions>;
hideLeftWindow<T extends UniNamespace.CommonOptions = UniNamespace.CommonOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.CommonOptions>;
showRightWindow<T extends UniNamespace.CommonOptions = UniNamespace.CommonOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.CommonOptions>;
hideRightWindow<T extends UniNamespace.CommonOptions = UniNamespace.CommonOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.CommonOptions>;
getProvider<T extends UniNamespace.GetProviderOptions = UniNamespace.GetProviderOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.GetProviderOptions>;
login<T extends UniNamespace.LoginOptions = UniNamespace.LoginOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.LoginOptions>;
checkSession<T extends UniNamespace.CheckSessionOptions = UniNamespace.CheckSessionOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.CheckSessionOptions>;
getUserInfo<T extends UniNamespace.GetUserInfoOptions = UniNamespace.GetUserInfoOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.GetUserInfoOptions>;
getUserProfile<T extends UniNamespace.GetUserProfileOptions = UniNamespace.GetUserProfileOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.GetUserProfileOptions>;
preLogin<T extends UniNamespace.PreLoginOptions = UniNamespace.PreLoginOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.PreLoginOptions>;
getCheckBoxState<T extends UniNamespace.GetCheckBoxStateOptions = UniNamespace.GetCheckBoxStateOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.GetCheckBoxStateOptions>;
share<T extends UniNamespace.ShareOptions = UniNamespace.ShareOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.ShareOptions>;
shareWithSystem<T extends UniNamespace.ShareWithSystemOptions = UniNamespace.ShareWithSystemOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.ShareWithSystemOptions>;
getPushClientId<T extends UniNamespace.GetPushClientIdOptions = UniNamespace.GetPushClientIdOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.GetPushClientIdOptions>;
requestPayment<T extends UniNamespace.RequestPaymentOptions = UniNamespace.RequestPaymentOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.RequestPaymentOptions>;
authorize<T extends UniNamespace.AuthorizeOptions = UniNamespace.AuthorizeOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.AuthorizeOptions>;
openSetting<T extends UniNamespace.OpenSettingOptions = UniNamespace.OpenSettingOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.OpenSettingOptions>;
getSetting<T extends UniNamespace.GetSettingOptions = UniNamespace.GetSettingOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.GetSettingOptions>;
chooseAddress<T extends UniNamespace.ChooseAddressOptions = UniNamespace.ChooseAddressOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.ChooseAddressOptions>;
chooseInvoiceTitle<T extends UniNamespace.ChooseInvoiceTitleOptions = UniNamespace.ChooseInvoiceTitleOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.ChooseInvoiceTitleOptions>;
navigateToMiniProgram<T extends UniNamespace.NavigateToMiniProgramOptions = UniNamespace.NavigateToMiniProgramOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.NavigateToMiniProgramOptions>;
navigateBackMiniProgram<T extends UniNamespace.NavigateBackMiniProgramOptions = UniNamespace.NavigateBackMiniProgramOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.NavigateBackMiniProgramOptions>;
setEnableDebug<T extends UniNamespace.SetEnableDebugOptions = UniNamespace.SetEnableDebugOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.SetEnableDebugOptions>;
getExtConfig<T extends UniNamespace.GetExtConfigOptions = UniNamespace.GetExtConfigOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.GetExtConfigOptions>;
showShareMenu<T extends UniNamespace.ShowShareMenuOptions = UniNamespace.ShowShareMenuOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.ShowShareMenuOptions>;
hideShareMenu<T extends UniNamespace.HideShareMenuOptions = UniNamespace.HideShareMenuOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.HideShareMenuOptions>;
setBackgroundColor<T extends UniNamespace.SetBackgroundColorOptions = UniNamespace.SetBackgroundColorOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.SetBackgroundColorOptions>;
setBackgroundTextStyle<T extends UniNamespace.SetBackgroundTextStyleOptions = UniNamespace.SetBackgroundTextStyleOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.SetBackgroundTextStyleOptions>;
startGyroscope<T extends UniNamespace.StartGyroscopeOptions = UniNamespace.StartGyroscopeOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.StartGyroscopeOptions>;
stopGyroscope<T extends UniNamespace.StopGyroscopeOptions = UniNamespace.StopGyroscopeOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.StopGyroscopeOptions>;
loadFontFace<T extends UniNamespace.LoadFontFaceOptions = UniNamespace.LoadFontFaceOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.LoadFontFaceOptions>;
startSoterAuthentication<T extends UniNamespace.StartSoterAuthenticationOptions = UniNamespace.StartSoterAuthenticationOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.StartSoterAuthenticationOptions>;
checkIsSupportSoterAuthentication<T extends UniNamespace.CheckIsSupportSoterAuthenticationOptions = UniNamespace.CheckIsSupportSoterAuthenticationOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.CheckIsSupportSoterAuthenticationOptions>;
checkIsSoterEnrolledInDevice<T extends UniNamespace.CheckIsSoterEnrolledInDeviceOptions = UniNamespace.CheckIsSoterEnrolledInDeviceOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.CheckIsSoterEnrolledInDeviceOptions>;
connectSocket<T extends UniNamespace.ConnectSocketOption = UniNamespace.ConnectSocketOption>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.ConnectSocketOption, UniNamespace.SocketTask>;
request<T extends UniNamespace.RequestOptions = UniNamespace.RequestOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.RequestOptions, UniNamespace.RequestTask>;
uploadFile<T extends UniNamespace.UploadFileOption = UniNamespace.UploadFileOption>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.UploadFileOption, UniNamespace.UploadTask>;
downloadFile<T extends UniNamespace.DownloadFileOption = UniNamespace.DownloadFileOption>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.DownloadFileOption, UniNamespace.DownloadTask>;
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,48 @@
declare namespace UniNamespace {
interface GeneralCallbackResult {
/**
* 错误信息
*/
errMsg: string;
}
/**
* 小程序错误事件的监听函数
*/
type OnAppErrorCallback = (
/** 错误信息,包含堆栈 */
error: string
) => void;
/**
* onError 传入的监听函数。不传此参数则移除所有监听函数。
*/
type OffAppErrorCallback = (res: GeneralCallbackResult) => void;
}
interface Uni {
/**
*
* 需要基础库: `2.1.2`
*
* 在插件中使用:不支持
*
* 监听小程序错误事件。如脚本错误或 API 调用报错等。该事件与 [`App.onError`](https://developers.weixin.qq.com/miniprogram/dev/reference/api/App.html#onerrorstring-error) 的回调时机与参数一致。
*
* 文档: [https://developers.weixin.qq.com/miniprogram/dev/api/base/app/app-event/wx.onError.html](https://developers.weixin.qq.com/miniprogram/dev/api/base/app/app-event/wx.onError.html)
*/
onError(listener: UniNamespace.OnAppErrorCallback): void;
/**
*
* 需要基础库: `2.1.2`
*
* 在插件中使用:不支持
*
* 移除小程序错误事件的监听函数
*
*
* 文档: [https://developers.weixin.qq.com/miniprogram/dev/api/base/app/app-event/wx.offError.html](https://developers.weixin.qq.com/miniprogram/dev/api/base/app/app-event/wx.offError.html)
*/
offError(listener?: UniNamespace.OffAppErrorCallback): void;
}

View File

@@ -0,0 +1,402 @@
import { AsyncOptions } from './Utils';
declare global {
namespace UniNamespace {
interface MapContext {
/**
* 获取当前地图中心的经纬度,返回的是 gcj02 坐标系,可以用于 uni.openLocation
*/
getCenterLocation(options: MapContextGetCenterLocationOptions): void;
/**
* 将地图中心移动到当前定位点需要配合map组件的show-location使用
*/
moveToLocation(options: MapContextMoveToLocationOptions): void;
/**
* 平移marker带动画
*/
translateMarker(options: MapContextTranslateMarkerOptions): void;
/**
* 缩放视野展示所有经纬度
*/
includePoints(options: MapContextIncludePointsOptions): void;
/**
* 获取当前地图的视野范围
*/
getRegion(options: MapContextGetRegionOptions): void;
/**
* 获取当前地图的缩放级别
*/
getScale(options: MapContextGetScaleOptions): void;
/**
* 添加个性化图层
*/
addCustomLayer?: (options: MapContextAddCustomLayerOptions) => void;
/**
* 创建自定义图片图层,图片会随着地图缩放而缩放
*/
addGroundOverlay(options: MapContextAddGroundOverlayOptions): void;
/**
* 添加 marker
*/
addMarkers(options: MapContextAddMarkersOptions): void;
/**
* 获取屏幕上的点对应的经纬度,坐标原点为地图左上角
*/
fromScreenLocation?: (options: MapContextFromScreenLocationOptions) => void;
/**
* 初始化点聚合的配置,未调用时采用默认配置
*/
initMarkerCluster(options: MapContextInitMarkerClusterOptions): void;
/**
* 沿指定路径移动 marker用于轨迹回放等场景。动画完成时触发回调事件若动画进行中对同一 marker 再次调用 moveAlong 方法,前一次的动画将被打断。
*/
moveAlong(options: MapContextMoveAlongOptions): void;
/**
* 拉起地图APP选择导航。
*/
openMapApp(options: MapContextOpenMapAppOptions): void;
/**
* 移除个性化图层
*/
removeCustomLayer(options: MapContextRemoveCustomLayerOptions): void;
/**
* 移除自定义图片图层
*/
removeGroundOverlay(options: MapContextRemoveGroundOverlayOptions): void;
/**
* 移除 marker
*/
removeMarkers(options: MapContextRemoveMarkersOptions): void;
/**
* 设置地图中心点偏移,向后向下为增长,屏幕比例范围(0.25~0.75),默认偏移为[0.5, 0.5]
*/
setCenterOffset?: (options: MapContextSetCenterOffsetOptions) => void;
/**
* 获取经纬度对应的屏幕坐标,坐标原点为地图左上角。
*/
toScreenLocation?: (options: MapContextToScreenLocationOptions) => void;
/**
* 更新自定义图片图层。
*/
updateGroundOverlay(options: MapContextUpdateGroundOverlayOptions): void;
/**
* 监听地图事件。
*/
on(event: 'markerClusterCreate' | 'markerClusterClick', callback: (...args: any[]) => any): void;
/**
* 获取原生地图对象 plus.maps.Map
*/
$getAppMap(): any;
}
interface MapContextGetCenterLocationOptions extends AsyncOptions {
/**
* 接口调用成功的回调函数 res = { longitude: "经度", latitude: "纬度"}
*/
success?: (result: LocationObject) => void;
}
interface MapContextMoveToLocationOptions extends AsyncOptions {
/**
* 纬度,浮点数,范围为-90~90负数表示南纬
*/
latitude?: number;
/**
* 经度,范围为-180~180负数表示西经
*/
longitude?: number;
}
interface LocationObject {
/**
* 纬度,浮点数,范围为-90~90负数表示南纬
*/
latitude: number;
/**
* 经度,范围为-180~180负数表示西经
*/
longitude: number;
}
interface MapContextTranslateMarkerOptions extends AsyncOptions {
/**
* 指定marker
*/
markerId: number;
/**
* 指定marker移动到的目标点
*/
destination: LocationObject;
/**
* 移动过程中是否自动旋转marker
*/
autoRotate: boolean;
/**
* marker的旋转角度
*/
rotate: number;
/**
* 平移和旋转同时进行默认值false仅微信小程序2.13.0支持)
*/
moveWithRotate?: boolean;
/**
* 动画持续时长默认值1000ms平移与旋转分别计算
*/
duration?: number;
/**
* 动画结束回调函数
*/
animationEnd?: (result: any) => void;
}
interface MapContextIncludePointsOptions extends AsyncOptions {
/**
* 要显示在可视区域内的坐标点列表,[{latitude, longitude}]
*/
points: LocationObject[];
/**
* 坐标点形成的矩形边缘到地图边缘的距离,单位像素。格式为[上,右,下,左]安卓上只能识别数组第一项上下左右的padding一致。开发者工具暂不支持padding参数。
*/
padding?: number[];
}
interface MapContextGetRegionOptions extends AsyncOptions {
/**
* 接口调用成功的回调函数res = {southwest, northeast},西南角与东北角的经纬度
*/
success?: (result: MapContextGetRegionResult) => void;
}
interface MapContextGetRegionResult {
/**
* 西南角的经纬度
*/
southwest: LocationObject;
/**
* 东北角的经纬度
*/
northeast: LocationObject;
}
interface MapContextGetScaleOptions extends AsyncOptions {
/**
* 接口调用成功的回调函数res = {scale}
*/
success?: (result: MapContextGetScaleResult) => void;
}
interface MapContextGetScaleResult {
/**
* 地图缩放级别
*/
scale: number;
}
interface MapContextAddCustomLayerOptions extends AsyncOptions {
/**
* 个性化图层id
*/
layerId: string;
}
interface MapContextAddGroundOverlayOptions extends AsyncOptions {
/**
* 图片图层 id
*/
id: string;
/**
* 图片路径,支持网络图片、临时路径、代码包路径
*/
src: string;
/**
* 图片覆盖的经纬度范围
*/
bounds: Bounds;
/**
* 是否可见
*/
visible?: boolean;
/**
* 图层绘制顺序
*/
zIndex?: number;
/**
* 图层透明度
*/
opacity?: number;
}
interface Bounds {
/**
* 西南角的经纬度
*/
southwest: LocationObject;
/**
* 东北角的经纬度
*/
northeast: LocationObject;
}
interface MapContextAddMarkersOptions extends AsyncOptions {
/**
* 同传入 map 组件的 marker 属性
*/
markers: any[];
/**
* 是否先清空地图上所有 marker
*/
clear: boolean;
}
interface MapContextFromScreenLocationOptions extends AsyncOptions {
/**
* x 坐标值
*/
x: number;
/**
* y 坐标值
*/
y: number;
/**
* 接口调用成功的回调函数
*/
success?: (result: LocationObject) => void;
}
interface MapContextInitMarkerClusterOptions extends AsyncOptions {
/**
* 启用默认的聚合样式
*/
enableDefaultStyle: boolean;
/**
* 点击已经聚合的标记点时是否实现聚合分离
*/
zoomOnClick: boolean;
/**
* 聚合算法的可聚合距离,即距离小于该值的点会聚合至一起,以像素为单位
*/
gridSize: number;
}
interface MapContextMoveAlongOptions extends AsyncOptions {
/**
* 指定 marker
*/
markerId: number;
/**
* 移动路径的坐标串,坐标点格式 {longitude, latitude}
*/
path: LocationObject[];
/**
* 根据路径方向自动改变 marker 的旋转角度
*/
autoRotate?: boolean;
/**
* 平滑移动的时间
*/
duration: number;
}
interface MapContextOpenMapAppOptions extends AsyncOptions {
/**
* 目的地名称
*/
destination: string;
/**
* 目的地纬度
*/
latitude: number;
/**
* 目的地经度
*/
longitude: number;
}
interface MapContextRemoveCustomLayerOptions extends AsyncOptions {
/**
* 个性化图层id
*/
layerId: string;
}
interface MapContextRemoveGroundOverlayOptions extends AsyncOptions {
/**
* 图片图层 id
*/
id: string;
}
interface MapContextRemoveMarkersOptions extends AsyncOptions {
/**
* 要被删除的marker的id属性组成的数组
*/
markerIds: any[];
}
interface MapContextSetCenterOffsetOptions {
/**
* 偏移量,两位数组
*/
offset: number[];
/**
* 接口调用成功的回调函数
*/
success?: (result: any) => void;
/**
* 接口调用失败的回调函数
*/
fail?: (result: any) => void;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (result: any) => void;
}
interface MapContextToScreenLocationOptions extends AsyncOptions {
/**
* 纬度
*/
latitude: number;
/**
* 经度
*/
longitude: number;
}
interface MapContextUpdateGroundOverlayOptions extends AsyncOptions {
/**
* 图片图层 id
*/
id: string;
/**
* 图片路径,支持网络图片、临时路径、代码包路径
*/
src: string;
/**
* 图片路径,支持网络图片、临时路径、代码包路径
*/
bounds: Bounds;
/**
* 是否可见
*/
visible?: boolean;
/**
* 图层绘制顺序
*/
zIndex?: number;
/**
* 图层透明度
*/
opacity?: number;
}
}
interface Uni {
/**
* 创建并返回 map 上下文 mapContext 对象
*
* 文档: [http://uniapp.dcloud.io/api/location/map?id=createmapcontext](http://uniapp.dcloud.io/api/location/map?id=createmapcontext)
*/
createMapContext(mapId: string, currentComponent?: any): UniNamespace.MapContext;
}
}

View File

@@ -0,0 +1,24 @@
declare namespace UniNamespace {
interface OnThemeChangeCallbackResult {
/**
* 主题名称
*/
theme: 'dark' | 'light';
}
type OnThemeChangeCallback = (res: OnThemeChangeCallbackResult) => void;
}
interface Uni {
/**
* 监听系统主题状态变化。
*
* 文档: [https://uniapp.dcloud.net.cn/api/system/theme.html#onthemechange](https://uniapp.dcloud.net.cn/api/system/theme.html#onthemechange)
*/
onThemeChange(callback: UniNamespace.OnThemeChangeCallback): void;
/**
* 取消监听系统主题状态变化。
*
* 文档: [https://uniapp.dcloud.net.cn/api/system/theme.html#offthemechange](https://uniapp.dcloud.net.cn/api/system/theme.html#offthemechange)
*/
offThemeChange(callback: UniNamespace.OnThemeChangeCallback): void;
}

View File

@@ -0,0 +1,43 @@
declare namespace UniNamespace {
interface OnUnhandledRejectionCallbackResult {
/**
* 被拒绝的 Promise 对象
*/
promise: Promise<any>;
/**
* 拒绝原因,一般是一个 Error 对象
*/
reason: string;
}
/**
* 未处理的 Promise 拒绝事件的回调函数
*/
type OnUnhandledRejectionCallback = (result: OnUnhandledRejectionCallbackResult) => void;
}
interface Uni {
/**
* 监听未处理的 Promise 拒绝事件。该事件与 `App.onUnhandledRejection` 的回调时机与参数一致。
*
* **注意**
*
*
* - 安卓平台暂时不支持该事件
* - 所有的 unhandledRejection 都可以被这一监听捕获,但只有 Error 类型的才会在小程序后台触发报警。
*
* 最低基础库: `2.10.0`
*
* 文档: [https://developers.weixin.qq.com/miniprogram/dev/api/base/app/app-event/wx.onUnhandledRejection.html](https://developers.weixin.qq.com/miniprogram/dev/api/base/app/app-event/wx.onUnhandledRejection.html)
*/
onUnhandledRejection(callback: UniNamespace.OnUnhandledRejectionCallback): void;
/**
* 取消监听未处理的 Promise 拒绝事件
*
* 最低基础库: `2.10.0`
*
* 文档: [https://developers.weixin.qq.com/miniprogram/dev/api/base/app/app-event/wx.offUnhandledRejection.html](https://developers.weixin.qq.com/miniprogram/dev/api/base/app/app-event/wx.offUnhandledRejection.html)
*/
offUnhandledRejection(callback: UniNamespace.OnUnhandledRejectionCallback): void;
}

View File

@@ -0,0 +1,14 @@
export interface AsyncOptions {
/**
* 接口调用成功的回调函数
*/
success?: (result: any) => void;
/**
* 接口调用失败的回调函数
*/
fail?: (result: any) => void;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (result: any) => void;
}

View File

@@ -0,0 +1,5 @@
/// <reference path="./ThemeChange.d.ts" />
/// <reference path="./UnhandledRejectiond.d.ts" />
/// <reference path="./Error.d.ts" />
/// <reference path="./MapContext.d.ts" />
/// <reference path="./request.d.ts" />

View File

@@ -0,0 +1,136 @@
declare namespace UniNamespace {
interface RequestOptions {
/**
* 资源url
*/
url: string;
/**
* 请求的参数
*/
data?: string | AnyObject | ArrayBuffer;
/**
* 设置请求的 headerheader 中不能设置 Referer。
*/
header?: any;
/**
* 默认为 GET
* 可以是OPTIONSGETHEADPOSTPUTDELETETRACECONNECT
*/
method?: 'OPTIONS' | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT';
/**
* 超时时间
*/
timeout?: number;
/**
* 如果设为json会尝试对返回的数据做一次 JSON.parse
*/
dataType?: string;
/**
* 设置响应的数据类型。合法值text、arraybuffer
*/
responseType?: string;
/**
* 验证 ssl 证书
*/
sslVerify?: boolean;
/**
* 跨域请求时是否携带凭证
*/
withCredentials?: boolean;
/**
* DNS解析时优先使用 ipv4
*/
firstIpv4?: boolean;
/**
* 开启 http2
*/
enableHttp2?: boolean;
/**
* 开启 quic
*/
enableQuic?: boolean;
/**
* 开启 cache
*/
enableCache?: boolean;
/**
* 是否开启 HttpDNS 服务。如开启,需要同时填入 httpDNSServiceId 。 HttpDNS 用法详见 [移动解析HttpDNS](https://developers.weixin.qq.com/miniprogram/dev/framework/ability/HTTPDNS.html)
*/
enableHttpDNS?: boolean;
/**
* HttpDNS 服务商 Id。 HttpDNS 用法详见 [移动解析HttpDNS](https://developers.weixin.qq.com/miniprogram/dev/framework/ability/HTTPDNS.html)
*/
httpDNSServiceId?: boolean;
/**
* 开启 transfer-encoding chunked
*/
enableChunked?: boolean;
/**
* wifi下使用移动网络发送请求
*/
forceCellularNetwork?: boolean;
/**
* 默认 false开启后可在headers中编辑cookie支付宝小程序10.2.33版本开始支持)
*/
enableCookie?: boolean;
/**
* 是否开启云加速(详见[云加速服务](https://smartprogram.baidu.com/docs/develop/extended/component-codeless/cloud-speed/introduction/)
*/
cloudCache?: object | boolean;
/**
* 控制当前请求是否延时至首屏内容渲染后发送
*/
defer?: boolean;
success?: (result: RequestSuccessCallbackResult) => void;
/**
* 失败的回调函数
*/
fail?: (result: GeneralCallbackResult) => void;
/**
* 结束的回调函数(调用成功、失败都会执行)
*/
complete?: (result: GeneralCallbackResult) => void;
}
interface RequestSuccessCallbackResult {
/**
* 开发者服务器返回的数据
*/
data: string | AnyObject | ArrayBuffer;
/**
* 开发者服务器返回的 HTTP 状态码
*/
statusCode: number;
/**
* 开发者服务器返回的 HTTP Response Header
*/
header: any;
/**
* 开发者服务器返回的 cookies格式为字符串数组
*/
cookies: string[];
}
interface RequestTask {
/**
* 中断请求任务
*/
abort(): void;
/**
* 监听 HTTP Response Header 事件
*/
onHeadersReceived(callback: (result: any) => void): void;
/**
* 取消监听 HTTP Response Header 事件
*/
offHeadersReceived(callback: (result: any) => void): void;
}
}
interface Uni {
/**
* 发起网络请求
*
* 文档: [http://uniapp.dcloud.io/api/request/request?id=request](http://uniapp.dcloud.io/api/request/request?id=request)
*/
request(options: UniNamespace.RequestOptions): UniNamespace.RequestTask;
}

View File

@@ -0,0 +1,23 @@
declare namespace UniNamespace {
interface OnMemoryWarningCallbackResult {
/**
* 仅 Android 有该字段,对应系统内存告警等级宏定义
*/
level: number;
}
type OnMemoryWarningCallback = (res: OnMemoryWarningCallbackResult) => void;
}
interface Uni {
/**
* 监听内存不足告警事件。
*
* 文档: [https://uniapp.dcloud.net.cn/api/system/memory.html#onmemorywarning](https://uniapp.dcloud.net.cn/api/system/memory.html#onmemorywarning)
*/
onMemoryWarning(callback: UniNamespace.OnMemoryWarningCallback): void;
/**
* 取消监听内存不足告警事件。不传入 callback 则取消所有监听。
*
* 文档: [https://uniapp.dcloud.net.cn/api/system/memory.html#offmemorywarning](https://uniapp.dcloud.net.cn/api/system/memory.html#offmemorywarning)
*/
offMemoryWarning(callback?: UniNamespace.OnMemoryWarningCallback): void;
}

View File

@@ -0,0 +1,18 @@
declare namespace UniNamespace {
type OnUserCaptureScreenCallback = (res?: { errMsg: string }) => void;
}
interface Uni {
/**
* 监听用户主动截屏事件,用户使用系统截屏按键截屏时触发此事件。
*
* 文档: [https://uniapp.dcloud.net.cn/api/system/capture-screen.html#onusercapturescreen](https://uniapp.dcloud.net.cn/api/system/capture-screen.html#onusercapturescreen)
*/
onUserCaptureScreen(callback: UniNamespace.OnUserCaptureScreenCallback): void;
/**
* 用户主动截屏事件。取消事件监听。
*
* 文档: [https://uniapp.dcloud.net.cn/api/system/capture-screen.html#offusercapturescreen](https://uniapp.dcloud.net.cn/api/system/capture-screen.html#offusercapturescreen)
*/
offUserCaptureScreen(callback: UniNamespace.OnUserCaptureScreenCallback): void;
}

View File

@@ -0,0 +1,386 @@
declare namespace UniNamespace {
interface WifiError {
/**
* 错误信息
*
* | 错误码 | 错误信息 | 说明 |
* | - | - | - |
* | 0 | ok | 正常 |
* | 12000 | not init | 未先调用 `startWifi` 接口 |
* | 12001 | system not support | 当前系统不支持相关能力 |
* | 12002 | password error Wi-Fi | 密码错误 |
* | 12003 | connection timeout | 连接超时, 仅 Android 支持 |
* | 12004 | duplicate request | 重复连接 Wi-Fi |
* | 12005 | wifi not turned on | Android 特有,未打开 Wi-Fi 开关 |
* | 12006 | gps not turned on | Android 特有,未打开 GPS 定位开关 |
* | 12007 | user denied | 用户拒绝授权链接 Wi-Fi |
* | 12008 | invalid SSID | 无效 SSID |
* | 12009 | system config err | 系统运营商配置拒绝连接 Wi-Fi |
* | 12010 | system internal error | 系统其他错误,需要在 errmsg 打印具体的错误原因 |
* | 12011 | weapp in background | 应用在后台无法配置 Wi-Fi |
* | 12013 | wifi config may be expired | 系统保存的 Wi-Fi 配置过期,建议忘记 Wi-Fi 后重试,仅 Android 支持 |
* | 12014 | invalid WEP / WPA password | iOS 特有,无效的 WEP / WPA 密码 |
*/
errMsg: string;
/**
* 错误码
*
* | 错误码 | 错误信息 | 说明 |
* | - | - | - |
* | 0 | ok | 正常 |
* | 12000 | not init | 未先调用 `startWifi` 接口 |
* | 12001 | system not support | 当前系统不支持相关能力 |
* | 12002 | password error Wi-Fi | 密码错误 |
* | 12003 | connection timeout | 连接超时, 仅 Android 支持 |
* | 12004 | duplicate request | 重复连接 Wi-Fi |
* | 12005 | wifi not turned on | Android 特有,未打开 Wi-Fi 开关 |
* | 12006 | gps not turned on | Android 特有,未打开 GPS 定位开关 |
* | 12007 | user denied | 用户拒绝授权链接 Wi-Fi |
* | 12008 | invalid SSID | 无效 SSID |
* | 12009 | system config err | 系统运营商配置拒绝连接 Wi-Fi |
* | 12010 | system internal error | 系统其他错误,需要在 errmsg 打印具体的错误原因 |
* | 12011 | weapp in background | 应用在后台无法配置 Wi-Fi |
* | 12013 | wifi config may be expired | 系统保存的 Wi-Fi 配置过期,建议忘记 Wi-Fi 后重试,仅 Android 支持 |
* | 12014 | invalid WEP / WPA password | iOS 特有,无效的 WEP / WPA 密码 |
*/
errCode: number;
}
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
type StartWifiCompleteCallback = (res: WifiError) => void;
/**
* 接口调用失败的回调函数
*/
type StartWifiFailCallback = (res: WifiError) => void;
/**
* 接口调用成功的回调函数
*/
type StartWifiSuccessCallback = (res: WifiError) => void;
interface StartWifiOption {
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: StartWifiCompleteCallback;
/**
* 接口调用失败的回调函数
*/
fail?: StartWifiFailCallback;
/**
* 接口调用成功的回调函数
*/
success?: StartWifiSuccessCallback;
}
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
type StopWifiCompleteCallback = (res: WifiError) => void;
/**
* 接口调用失败的回调函数
*/
type StopWifiFailCallback = (res: WifiError) => void;
/**
* 接口调用成功的回调函数
*/
type StopWifiSuccessCallback = (res: WifiError) => void;
interface StopWifiOption {
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: StopWifiCompleteCallback;
/**
* 接口调用失败的回调函数
*/
fail?: StopWifiFailCallback;
/**
* 接口调用成功的回调函数
*/
success?: StopWifiSuccessCallback;
}
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
type ConnectWifiCompleteCallback = (res: WifiError) => void;
/**
* 接口调用失败的回调函数
*/
type ConnectWifiFailCallback = (res: WifiError) => void;
/**
* 接口调用成功的回调函数
*/
type ConnectWifiSuccessCallback = (res: WifiError) => void;
interface ConnectWifiOption {
/**
* Wi-Fi 设备 SSID
*/
SSID: string;
/**
* Wi-Fi 设备 BSSID
*/
BSSID?: string;
/**
* Wi-Fi 设备密码
*/
password: string;
/**
* 需要基础库: `2.12.0`
*
* 跳转到系统设置页进行连接
*/
maunal?: boolean;
/**
* 需要基础库: `2.22.0`
*
* 是否需要返回部分 Wi-Fi 信息,仅安卓生效
*/
partialInfo?: boolean;
/**
* 接口调用成功的回调函数
*/
success?: ConnectWifiSuccessCallback;
/**
* 接口调用失败的回调函数
*/
fail?: ConnectWifiFailCallback;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: ConnectWifiCompleteCallback;
}
interface WifiInfo {
/**
* Wi-Fi 的 SSID
*/
SSID: string;
/**
* Wi-Fi 的 BSSID
*/
BSSID: string;
/**
* Wi-Fi 是否安全
*/
secure: boolean;
/**
* Wi-Fi 信号强度, 安卓取值 0 100 iOS 取值 0 1 ,值越大强度越大
*/
signalStrength: number;
/**
* Wi-Fi 频段单位 MHz
*/
frequency: number;
}
interface OnWifiConnectedListenerResult {
/**
* Wi-Fi 信息
*
* 文档: [https://uniapp.dcloud.net.cn/api/system/wifi.html#WifiInfo](https://uniapp.dcloud.net.cn/api/system/wifi.html#WifiInfo)
*/
wifi: WifiInfo;
}
/**
* 连接上 Wi-Fi 的事件的监听函数
*/
type OnWifiConnectedCallback = (
result: OnWifiConnectedListenerResult
) => void;
/**
* onWifiConnected 传入的监听函数。不传此参数则移除所有监听函数。
*/
type OffWifiConnectedCallback = (
result: OnWifiConnectedListenerResult
) => void;
interface OnWifiConnectedWithPartialInfoListenerResult {
/**
*
* 只包含 SSID 属性的 WifiInfo 对象
*
* 文档: [https://uniapp.dcloud.net.cn/api/system/wifi.html#WifiInfo](https://uniapp.dcloud.net.cn/api/system/wifi.html#WifiInfo)
*/
wifi: WifiInfo;
}
/**
* 连接上 Wi-Fi 的事件的监听函数
*/
type OnWifiConnectedWithPartialInfoCallback = (
result: OnWifiConnectedWithPartialInfoListenerResult
) => void;
interface GetConnectedWifiSuccessCallbackResult {
/**
* Wi-Fi 信息
*
* 文档: [https://uniapp.dcloud.net.cn/api/system/wifi.html#WifiInfo](https://uniapp.dcloud.net.cn/api/system/wifi.html#WifiInfo)
*/
wifi: WifiInfo;
errMsg: string;
}
/**
* 接口调用成功的回调函数
*/
type GetConnectedWifiSuccessCallback = (
result: GetConnectedWifiSuccessCallbackResult
) => void;
/**
* 接口调用失败的回调函数
*/
type GetConnectedWifiFailCallback = (res: WifiError) => void;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
type GetConnectedWifiCompleteCallback = (res: WifiError) => void;
interface GetConnectedWifiOption {
/**
* 是否需要返回部分 Wi-Fi 信息
*/
partialInfo?: boolean;
/**
* 接口调用成功的回调函数
*/
success?: GetConnectedWifiSuccessCallback;
/**
* 接口调用失败的回调函数
*/
fail?: GetConnectedWifiFailCallback;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: GetConnectedWifiCompleteCallback;
}
/**
* 接口调用成功的回调函数
*/
type GetWifiListSuccessCallback = (res: WifiError) => void;
/**
* 接口调用失败的回调函数
*/
type GetWifiListFailCallback = (res: WifiError) => void;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
type GetWifiListCompleteCallback = (res: WifiError) => void;
interface GetWifiListOption {
/**
* 接口调用成功的回调函数
*/
success?: GetWifiListSuccessCallback;
/**
* 接口调用失败的回调函数
*/
fail?: GetWifiListFailCallback;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: GetWifiListCompleteCallback;
}
interface OnGetWifiListListenerResult {
/**
* Wi-Fi 列表数据
*/
wifiList: WifiInfo[];
}
/**
* 获取到 Wi-Fi 列表数据事件的监听函数
*/
type OnGetWifiListCallback = (result: OnGetWifiListListenerResult) => void;
/**
* onGetWifiList 传入的监听函数。不传此参数则移除所有监听函数。
*/
type OffGetWifiListCallback = (result: OnGetWifiListListenerResult) => void;
/**
* onWifiConnectedWithPartialInfo 传入的监听函数。不传此参数则移除所有监听函数。
*/
type OffWifiConnectedWithPartialInfoCallback = (
result: OnWifiConnectedWithPartialInfoListenerResult
) => void;
}
interface Uni {
/**
* 初始化 Wi-Fi 模块
*
* 文档: [https://uniapp.dcloud.net.cn/api/system/wifi.html#startwifi](https://uniapp.dcloud.net.cn/api/system/wifi.html#startwifi)
*/
startWifi(option?: UniNamespace.StartWifiOption): void;
/**
* 关闭 Wi-Fi 模块
*
* 文档: [https://uniapp.dcloud.net.cn/api/system/wifi.html#stopwifi](https://uniapp.dcloud.net.cn/api/system/wifi.html#stopwifi)
*/
stopWifi(option?: UniNamespace.StopWifiOption): void;
/**
* 连接 Wi-Fi。若已知 Wi-Fi 信息,可以直接利用该接口连接。
*
* 文档: [https://uniapp.dcloud.net.cn/api/system/wifi.html#connectwifi](https://uniapp.dcloud.net.cn/api/system/wifi.html#connectwifi)
*/
connectWifi(option: UniNamespace.ConnectWifiOption): void;
/**
* 监听连接上 Wi-Fi 的事件。
*
* 文档: [https://uniapp.dcloud.net.cn/api/system/wifi.html#onwificonnected](https://uniapp.dcloud.net.cn/api/system/wifi.html#onwificonnected)
*/
onWifiConnected(listener: UniNamespace.OnWifiConnectedCallback): void;
/**
* 移除连接上 Wi-Fi 的事件的监听函数
*
* 文档: [https://uniapp.dcloud.net.cn/api/system/wifi.html#offwificonnected](https://uniapp.dcloud.net.cn/api/system/wifi.html#offwificonnected)
*/
offWifiConnected(listener?: UniNamespace.OffWifiConnectedCallback): void;
/**
* 获取已连接的 Wi-Fi 信息。
*
* 文档: [https://uniapp.dcloud.net.cn/api/system/wifi.html#getconnectedwifi](https://uniapp.dcloud.net.cn/api/system/wifi.html#getconnectedwifi)
*/
getConnectedWifi(option: UniNamespace.GetConnectedWifiOption): void;
/**
* 请求获取 Wi-Fi 列表。wifiList 数据会在 onGetWifiList 注册的回调中返回。
*
* 文档: [https://uniapp.dcloud.net.cn/api/system/wifi.html#getwifilist](https://uniapp.dcloud.net.cn/api/system/wifi.html#getwifilist)
*/
getWifiList(option?: UniNamespace.GetWifiListOption): void;
/**
* 监听获取到 Wi-Fi 列表数据事件。
*
* 文档: [https://uniapp.dcloud.net.cn/api/system/wifi.html#ongetwifilist](https://uniapp.dcloud.net.cn/api/system/wifi.html#ongetwifilist)
*/
onGetWifiList(listener: UniNamespace.OnGetWifiListCallback): void;
/**
* 移除获取到 Wi-Fi 列表数据事件的监听函数
*
* 文档: [https://uniapp.dcloud.net.cn/api/system/wifi.html#offgetwifilist](https://uniapp.dcloud.net.cn/api/system/wifi.html#offgetwifilist)
*/
offGetWifiList(listener?: UniNamespace.OffGetWifiListCallback): void;
/**
* 监听连接上 Wi-Fi 的事件。
*
* 文档: [https://uniapp.dcloud.net.cn/api/system/wifi.html#onwificonnectedwithpartialinfo](https://uniapp.dcloud.net.cn/api/system/wifi.html#onwificonnectedwithpartialinfo)
*/
onWifiConnectedWithPartialInfo(listener: UniNamespace.OnWifiConnectedWithPartialInfoCallback): void;
/**
* 移除连接上 Wi-Fi 的事件的监听函数
*
* 文档: [https://uniapp.dcloud.net.cn/api/system/wifi.html#offwificonnectedwithpartialinfo](https://uniapp.dcloud.net.cn/api/system/wifi.html#offwificonnectedwithpartialinfo)
*/
offWifiConnectedWithPartialInfo(listener?: UniNamespace.OffWifiConnectedWithPartialInfoCallback): void;
}

View File

@@ -0,0 +1,37 @@
declare namespace UniNamespace {
interface GetBatteryInfoSuccessCallbackResult {
/**
* 是否正在充电中
*/
isCharging: boolean;
/**
* 设备电量,范围 1 - 100
*/
level: number;
errMsg: string;
}
interface GetBatteryInfoOption {
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (result: any) => void;
/**
* 接口调用失败的回调函数
*/
fail?: (result: any) => void;
/**
* 接口调用成功的回调函数
*/
success?: (result: GetBatteryInfoSuccessCallbackResult) => void;
}
}
interface Uni {
/**
* 获取设备电量
*
* 文档: [https://uniapp.dcloud.net.cn/api/system/batteryInfo.html](https://uniapp.dcloud.net.cn/api/system/batteryInfo.html)
*/
getBatteryInfo(option?: UniNamespace.GetBatteryInfoOption): void;
}

View File

@@ -0,0 +1,4 @@
/// <reference path="./getBatteryInfo.d.ts" />
/// <reference path="./MemoryWarning.d.ts" />
/// <reference path="./UserCaptureScreen.d.ts" />
/// <reference path="./Wifi.d.ts" />

View File

@@ -0,0 +1,3 @@
/// <reference path="./legacy/uni.d.ts" />
/// <reference path="./base/index.d.ts" />
/// <reference path="./ext/index.d.ts" />

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,182 @@
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Tools = {}));
})(this, (function (exports) { 'use strict';
/**
* Make a map and return a function for checking if a key
* is in that map.
* IMPORTANT: all calls of this function must be prefixed with
* \/\*#\_\_PURE\_\_\*\/
* So that rollup can tree-shake them if necessary.
*/
(process.env.NODE_ENV !== 'production')
? Object.freeze({})
: {};
(process.env.NODE_ENV !== 'production') ? Object.freeze([]) : [];
const hasOwnProperty = Object.prototype.hasOwnProperty;
const hasOwn = (val, key) => hasOwnProperty.call(val, key);
const ACTION_TYPE_PAGE_CREATE = 1;
const ACTION_TYPE_PAGE_CREATED = 2;
const ACTION_TYPE_CREATE = 3;
const ACTION_TYPE_INSERT = 4;
const ACTION_TYPE_REMOVE = 5;
const ACTION_TYPE_SET_ATTRIBUTE = 6;
const ACTION_TYPE_REMOVE_ATTRIBUTE = 7;
const ACTION_TYPE_ADD_EVENT = 8;
const ACTION_TYPE_REMOVE_EVENT = 9;
const ACTION_TYPE_SET_TEXT = 10;
const ACTION_TYPE_ADD_WXS_EVENT = 12;
const ACTION_TYPE_DICT = 0;
function createGetDict(dict) {
if (!dict.length) {
return (v) => v;
}
const getDict = (value, includeValue = true) => {
if (typeof value === 'number') {
return dict[value];
}
const res = {};
value.forEach(([n, v]) => {
if (includeValue) {
res[getDict(n)] = getDict(v);
}
else {
res[getDict(n)] = v;
}
});
return res;
};
return getDict;
}
function decodeActions(actions) {
const [type, dict] = actions[0];
if (type !== ACTION_TYPE_DICT) {
return actions;
}
const getDict = createGetDict(dict);
return actions.map((action) => {
switch (action[0]) {
case ACTION_TYPE_DICT:
return action;
case ACTION_TYPE_PAGE_CREATE:
return decodePageCreateAction(action);
case ACTION_TYPE_PAGE_CREATED:
return decodePageCreatedAction(action);
case ACTION_TYPE_CREATE:
return decodeCreateAction(action, getDict);
case ACTION_TYPE_INSERT:
return decodeInsertAction(action, getDict);
case ACTION_TYPE_REMOVE:
return decodeRemoveAction(action);
case ACTION_TYPE_SET_ATTRIBUTE:
return decodeSetAttributeAction(action, getDict);
case ACTION_TYPE_REMOVE_ATTRIBUTE:
return decodeRemoveAttributeAction(action, getDict);
case ACTION_TYPE_ADD_EVENT:
return decodeAddEventAction(action, getDict);
case ACTION_TYPE_ADD_WXS_EVENT:
return decodeAddWxsEventAction(action, getDict);
case ACTION_TYPE_REMOVE_EVENT:
return decodeRemoveEventAction(action, getDict);
case ACTION_TYPE_SET_TEXT:
return decodeSetTextAction(action, getDict);
}
});
}
function decodePageCreateAction([, pageCreateData]) {
return ['pageCreate', pageCreateData];
}
function decodePageCreatedAction([]) {
return ['pageCreated'];
}
function decodeNodeJson(getDict, nodeJson) {
if (!nodeJson) {
return;
}
if (hasOwn(nodeJson, 'a')) {
nodeJson.a = getDict(nodeJson.a);
}
if (hasOwn(nodeJson, 'e')) {
nodeJson.e = getDict(nodeJson.e, false);
}
if (hasOwn(nodeJson, 'w')) {
nodeJson.w = getWxsEventDict(nodeJson.w, getDict);
}
if (hasOwn(nodeJson, 's')) {
nodeJson.s = getDict(nodeJson.s);
}
if (hasOwn(nodeJson, 't')) {
nodeJson.t = getDict(nodeJson.t);
}
return nodeJson;
}
function getWxsEventDict(w, getDict) {
const res = {};
w.forEach(([name, [wxsEvent, flag]]) => {
res[getDict(name)] = [getDict(wxsEvent), flag];
});
return res;
}
function decodeCreateAction([, nodeId, nodeName, parentNodeId, refNodeId, nodeJson], getDict) {
return [
'create',
nodeId,
getDict(nodeName),
parentNodeId,
refNodeId,
decodeNodeJson(getDict, nodeJson),
];
}
function decodeInsertAction([, ...action], getDict) {
return [
'insert',
action[0],
action[1],
action[2],
action[3] ? decodeNodeJson(getDict, action[3]) : {},
];
}
function decodeRemoveAction([, ...action]) {
return ['remove', ...action];
}
function decodeAddEventAction([, ...action], getDict) {
return ['addEvent', action[0], getDict(action[1]), action[2]];
}
function decodeAddWxsEventAction([, ...action], getDict) {
return [
'addWxsEvent',
action[0],
getDict(action[1]),
getDict(action[2]),
action[3],
];
}
function decodeRemoveEventAction([, ...action], getDict) {
return ['removeEvent', action[0], getDict(action[1])];
}
function decodeSetAttributeAction([, ...action], getDict) {
return [
'setAttr',
action[0],
getDict(action[1]),
getDict(action[2]),
];
}
function decodeRemoveAttributeAction([, ...action], getDict) {
return ['removeAttr', action[0], getDict(action[1])];
}
function decodeSetTextAction([, ...action], getDict) {
return ['setText', action[0], getDict(action[1])];
}
exports.createGetDict = createGetDict;
exports.decodeActions = decodeActions;
exports.decodeNodeJson = decodeNodeJson;
}));

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,13 @@
'use strict';
var appVite = require('@dcloudio/uni-app-vite');
var appUVue = require('@dcloudio/uni-app-uts');
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
var appVite__default = /*#__PURE__*/_interopDefault(appVite);
var appUVue__default = /*#__PURE__*/_interopDefault(appUVue);
var index = [process.env.UNI_APP_X === 'true' ? appUVue__default.default : appVite__default.default];
module.exports = index;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,276 @@
import { invokeArrayFns, isUniLifecycleHook, ON_LOAD, ON_SHOW, LINEFEED, RENDERJS_MODULES, formatLog, WXS_PROTOCOL, WXS_MODULES, UniLifecycleHooks, ON_ERROR, invokeCreateErrorHandler, invokeCreateVueAppHook } from '@dcloudio/uni-shared';
import { isString, isArray, isFunction } from '@vue/shared';
import { injectHook } from 'vue';
function getCurrentPage() {
const pages = getCurrentPages();
const len = pages.length;
if (len) {
return pages[len - 1];
}
}
function getCurrentPageVm() {
const page = getCurrentPage();
if (page) {
return page.$vm;
}
}
function invokeHook(vm, name, args) {
if (isString(vm)) {
args = name;
name = vm;
vm = getCurrentPageVm();
}
else if (typeof vm === 'number') {
const page = getCurrentPages().find((page) => page.$page.id === vm);
if (page) {
vm = page.$vm;
}
else {
vm = getCurrentPageVm();
}
}
if (!vm) {
return;
}
// 兼容 nvue
{
if (vm.__call_hook) {
return vm.__call_hook(name, args);
}
}
const hooks = vm.$[name];
return hooks && invokeArrayFns(hooks, args);
}
function injectLifecycleHook(name, hook, publicThis, instance) {
if (isFunction(hook)) {
injectHook(name, hook.bind(publicThis), instance);
}
}
function initHooks(options, instance, publicThis) {
var _a;
const mpType = options.mpType || publicThis.$mpType;
if (!mpType || mpType === 'component') {
// 仅 App,Page 类型支持在 options 中配置 on 生命周期,组件可以使用组合式 API 定义页面生命周期
return;
}
Object.keys(options).forEach((name) => {
if (isUniLifecycleHook(name, options[name], false)) {
const hooks = options[name];
if (isArray(hooks)) {
hooks.forEach((hook) => injectLifecycleHook(name, hook, publicThis, instance));
}
else {
injectLifecycleHook(name, hooks, publicThis, instance);
}
}
});
if (mpType === 'page') {
instance.__isVisible = true;
// 直接触发页面 onLoad、onShow 组件内的 onLoad 和 onShow 在注册时,直接触发一次
try {
invokeHook(publicThis, ON_LOAD, instance.attrs.__pageQuery);
delete instance.attrs.__pageQuery;
if (((_a = publicThis.$page) === null || _a === void 0 ? void 0 : _a.openType) !== 'preloadPage') {
invokeHook(publicThis, ON_SHOW);
}
}
catch (e) {
console.error(e.message + LINEFEED + e.stack);
}
}
}
function initRenderjs(options, instance) {
initModules(instance, options.$renderjs, options['$' + RENDERJS_MODULES]);
}
function initModules(instance, modules, moduleIds = {}) {
if (!isArray(modules)) {
return;
}
const ownerId = instance.uid;
// 在vue的定制内核中通过$wxsModules来判断事件函数源码中是否包含该模块调用
// !$wxsModules.find(module => invokerSourceCode.indexOf('.' + module + '.') > -1)
const $wxsModules = (instance.$wxsModules ||
(instance.$wxsModules = []));
const ctx = instance.ctx;
modules.forEach((module) => {
if (moduleIds[module]) {
ctx[module] = proxyModule(ownerId, moduleIds[module], module);
$wxsModules.push(module);
}
else {
if ((process.env.NODE_ENV !== 'production')) {
console.error(formatLog('initModules', modules, moduleIds));
}
}
});
}
function proxyModule(ownerId, moduleId, module) {
const target = {};
return new Proxy(target, {
get(_, p) {
return (target[p] ||
(target[p] = createModuleFunction(ownerId, moduleId, module, p)));
},
});
}
function createModuleFunction(ownerId, moduleId, module, name) {
const target = () => { };
const toJSON = () => WXS_PROTOCOL + JSON.stringify([ownerId, moduleId, module + '.' + name]);
return new Proxy(target, {
get(_, p) {
if (p === 'toJSON') {
return toJSON;
}
return (target[p] ||
(target[p] = createModuleFunction(ownerId, moduleId, module + '.' + name, p)));
},
apply(_target, _thisArg, args) {
return (WXS_PROTOCOL +
JSON.stringify([ownerId, moduleId, module + '.' + name, [...args]]));
},
});
}
function initWxs(options, instance) {
initModules(instance, options.$wxs, options['$' + WXS_MODULES]);
}
function applyOptions(options, instance, publicThis) {
{
initWxs(options, instance);
initRenderjs(options, instance);
}
initHooks(options, instance, publicThis);
}
function set(target, key, val) {
return (target[key] = val);
}
function createErrorHandler(app) {
return function errorHandler(err, instance, _info) {
if (!instance) {
throw err;
}
const appInstance = app._instance;
if (!appInstance || !appInstance.proxy) {
throw err;
}
{
invokeHook(appInstance.proxy, ON_ERROR, err);
}
};
}
function mergeAsArray(to, from) {
return to ? [...new Set([].concat(to, from))] : from;
}
function initOptionMergeStrategies(optionMergeStrategies) {
UniLifecycleHooks.forEach((name) => {
optionMergeStrategies[name] = mergeAsArray;
});
}
let realAtob;
const b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
const b64re = /^(?:[A-Za-z\d+/]{4})*?(?:[A-Za-z\d+/]{2}(?:==)?|[A-Za-z\d+/]{3}=?)?$/;
if (typeof atob !== 'function') {
realAtob = function (str) {
str = String(str).replace(/[\t\n\f\r ]+/g, '');
if (!b64re.test(str)) {
throw new Error("Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.");
}
// Adding the padding if missing, for semplicity
str += '=='.slice(2 - (str.length & 3));
var bitmap;
var result = '';
var r1;
var r2;
var i = 0;
for (; i < str.length;) {
bitmap =
(b64.indexOf(str.charAt(i++)) << 18) |
(b64.indexOf(str.charAt(i++)) << 12) |
((r1 = b64.indexOf(str.charAt(i++))) << 6) |
(r2 = b64.indexOf(str.charAt(i++)));
result +=
r1 === 64
? String.fromCharCode((bitmap >> 16) & 255)
: r2 === 64
? String.fromCharCode((bitmap >> 16) & 255, (bitmap >> 8) & 255)
: String.fromCharCode((bitmap >> 16) & 255, (bitmap >> 8) & 255, bitmap & 255);
}
return result;
};
}
else {
// 注意atob只能在全局对象上调用例如`const Base64 = {atob};Base64.atob('xxxx')`是错误的用法
realAtob = atob;
}
function b64DecodeUnicode(str) {
return decodeURIComponent(realAtob(str)
.split('')
.map(function (c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
})
.join(''));
}
function getCurrentUserInfo() {
const token = uni.getStorageSync('uni_id_token') || '';
const tokenArr = token.split('.');
if (!token || tokenArr.length !== 3) {
return {
uid: null,
role: [],
permission: [],
tokenExpired: 0,
};
}
let userInfo;
try {
userInfo = JSON.parse(b64DecodeUnicode(tokenArr[1]));
}
catch (error) {
throw new Error('获取当前用户信息出错,详细错误信息为:' + error.message);
}
userInfo.tokenExpired = userInfo.exp * 1000;
delete userInfo.exp;
delete userInfo.iat;
return userInfo;
}
function uniIdMixin(globalProperties) {
globalProperties.uniIDHasRole = function (roleId) {
const { role } = getCurrentUserInfo();
return role.indexOf(roleId) > -1;
};
globalProperties.uniIDHasPermission = function (permissionId) {
const { permission } = getCurrentUserInfo();
return this.uniIDHasRole('admin') || permission.indexOf(permissionId) > -1;
};
globalProperties.uniIDTokenValid = function () {
const { tokenExpired } = getCurrentUserInfo();
return tokenExpired > Date.now();
};
}
function initApp(app) {
const appConfig = app._context.config;
appConfig.errorHandler = invokeCreateErrorHandler(app, createErrorHandler);
initOptionMergeStrategies(appConfig.optionMergeStrategies);
const globalProperties = appConfig.globalProperties;
{
uniIdMixin(globalProperties);
}
{
globalProperties.$set = set;
globalProperties.$applyOptions = applyOptions;
}
{
invokeCreateVueAppHook(app);
}
}
export { initApp };

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,53 @@
{
"name": "@dcloudio/uni-app-plus",
"version": "3.0.0-3090520231028001",
"description": "@dcloudio/uni-app-plus",
"files": [
"dist",
"lib",
"style"
],
"sideEffects": [
"lib/automator.js"
],
"repository": {
"type": "git",
"url": "git+https://github.com/dcloudio/uni-app.git",
"directory": "packages/uni-app-plus"
},
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/dcloudio/uni-app/issues"
},
"gitHead": "33e807d66e1fe47e2ee08ad9c59247e37b8884da",
"uni-app": {
"name": "uni-app-plus",
"apply": [
"app"
],
"uvue": true,
"main": "dist/uni.compiler.js"
},
"dependencies": {
"@dcloudio/uni-app-uts": "3.0.0-3090520231028001",
"@dcloudio/uni-app-vite": "3.0.0-3090520231028001",
"@dcloudio/uni-app-vue": "3.0.0-3090520231028001",
"debug": "^4.3.3",
"fs-extra": "^10.0.0",
"licia": "^1.29.0",
"postcss-selector-parser": "^6.0.6"
},
"devDependencies": {
"@dcloudio/uni-cli-shared": "3.0.0-3090520231028001",
"@dcloudio/uni-components": "3.0.0-3090520231028001",
"@dcloudio/uni-h5": "3.0.0-3090520231028001",
"@dcloudio/uni-i18n": "3.0.0-3090520231028001",
"@dcloudio/uni-shared": "3.0.0-3090520231028001",
"@types/pako": "1.0.2",
"@vue/compiler-sfc": "3.2.47",
"autoprefixer": "^10.4.14",
"pako": "^1.0.11",
"postcss": "^8.4.21",
"vue": "3.2.47"
}
}

View File

@@ -0,0 +1,17 @@
uni-cover-image {
display: block;
line-height: 1.2;
overflow: hidden;
height: 100%;
width: 100%;
pointer-events: auto;
}
uni-cover-image[hidden] {
display: none;
}
uni-cover-image .uni-cover-image {
width: 100%;
height: 100%;
}

View File

@@ -0,0 +1,29 @@
uni-cover-view {
display: block;
line-height: 1.2;
overflow: hidden;
white-space: nowrap;
pointer-events: auto;
}
uni-cover-view[hidden] {
display: none;
}
uni-cover-view .uni-cover-view {
width: 100%;
height: 100%;
visibility: hidden;
text-overflow: inherit;
white-space: inherit;
-webkit-align-items: inherit;
align-items: inherit;
-webkit-justify-content: inherit;
justify-content: inherit;
-webkit-flex-direction: inherit;
flex-direction: inherit;
-webkit-flex-wrap: inherit;
flex-wrap: inherit;
display: inherit;
overflow: inherit;
}

View File

@@ -0,0 +1,85 @@
* {
margin: 0;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
-webkit-tap-highlight-color: transparent;
}
html,
body {
-webkit-user-select: none;
user-select: none;
width: 100%;
}
html {
height: 100%;
height: 100vh;
width: 100%;
width: 100vw;
}
body {
overflow-x: hidden;
background-color: white;
height:100%;
}
#app{
height: 100%;
}
input[type='search']::-webkit-search-cancel-button {
display: none;
}
.uni-loading,
uni-button[loading]:before {
background: transparent
url('data:image/svg+xml;base64, PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMjAiIGhlaWdodD0iMTIwIiB2aWV3Qm94PSIwIDAgMTAwIDEwMCI+PHBhdGggZmlsbD0ibm9uZSIgZD0iTTAgMGgxMDB2MTAwSDB6Ii8+PHJlY3Qgd2lkdGg9IjciIGhlaWdodD0iMjAiIHg9IjQ2LjUiIHk9IjQwIiBmaWxsPSIjRTlFOUU5IiByeD0iNSIgcnk9IjUiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDAgLTMwKSIvPjxyZWN0IHdpZHRoPSI3IiBoZWlnaHQ9IjIwIiB4PSI0Ni41IiB5PSI0MCIgZmlsbD0iIzk4OTY5NyIgcng9IjUiIHJ5PSI1IiB0cmFuc2Zvcm09InJvdGF0ZSgzMCAxMDUuOTggNjUpIi8+PHJlY3Qgd2lkdGg9IjciIGhlaWdodD0iMjAiIHg9IjQ2LjUiIHk9IjQwIiBmaWxsPSIjOUI5OTlBIiByeD0iNSIgcnk9IjUiIHRyYW5zZm9ybT0icm90YXRlKDYwIDc1Ljk4IDY1KSIvPjxyZWN0IHdpZHRoPSI3IiBoZWlnaHQ9IjIwIiB4PSI0Ni41IiB5PSI0MCIgZmlsbD0iI0EzQTFBMiIgcng9IjUiIHJ5PSI1IiB0cmFuc2Zvcm09InJvdGF0ZSg5MCA2NSA2NSkiLz48cmVjdCB3aWR0aD0iNyIgaGVpZ2h0PSIyMCIgeD0iNDYuNSIgeT0iNDAiIGZpbGw9IiNBQkE5QUEiIHJ4PSI1IiByeT0iNSIgdHJhbnNmb3JtPSJyb3RhdGUoMTIwIDU4LjY2IDY1KSIvPjxyZWN0IHdpZHRoPSI3IiBoZWlnaHQ9IjIwIiB4PSI0Ni41IiB5PSI0MCIgZmlsbD0iI0IyQjJCMiIgcng9IjUiIHJ5PSI1IiB0cmFuc2Zvcm09InJvdGF0ZSgxNTAgNTQuMDIgNjUpIi8+PHJlY3Qgd2lkdGg9IjciIGhlaWdodD0iMjAiIHg9IjQ2LjUiIHk9IjQwIiBmaWxsPSIjQkFCOEI5IiByeD0iNSIgcnk9IjUiIHRyYW5zZm9ybT0icm90YXRlKDE4MCA1MCA2NSkiLz48cmVjdCB3aWR0aD0iNyIgaGVpZ2h0PSIyMCIgeD0iNDYuNSIgeT0iNDAiIGZpbGw9IiNDMkMwQzEiIHJ4PSI1IiByeT0iNSIgdHJhbnNmb3JtPSJyb3RhdGUoLTE1MCA0NS45OCA2NSkiLz48cmVjdCB3aWR0aD0iNyIgaGVpZ2h0PSIyMCIgeD0iNDYuNSIgeT0iNDAiIGZpbGw9IiNDQkNCQ0IiIHJ4PSI1IiByeT0iNSIgdHJhbnNmb3JtPSJyb3RhdGUoLTEyMCA0MS4zNCA2NSkiLz48cmVjdCB3aWR0aD0iNyIgaGVpZ2h0PSIyMCIgeD0iNDYuNSIgeT0iNDAiIGZpbGw9IiNEMkQyRDIiIHJ4PSI1IiByeT0iNSIgdHJhbnNmb3JtPSJyb3RhdGUoLTkwIDM1IDY1KSIvPjxyZWN0IHdpZHRoPSI3IiBoZWlnaHQ9IjIwIiB4PSI0Ni41IiB5PSI0MCIgZmlsbD0iI0RBREFEQSIgcng9IjUiIHJ5PSI1IiB0cmFuc2Zvcm09InJvdGF0ZSgtNjAgMjQuMDIgNjUpIi8+PHJlY3Qgd2lkdGg9IjciIGhlaWdodD0iMjAiIHg9IjQ2LjUiIHk9IjQwIiBmaWxsPSIjRTJFMkUyIiByeD0iNSIgcnk9IjUiIHRyYW5zZm9ybT0icm90YXRlKC0zMCAtNS45OCA2NSkiLz48L3N2Zz4=')
no-repeat;
}
.uni-loading {
width: 20px;
height: 20px;
display: inline-block;
vertical-align: middle;
animation: uni-loading 1s steps(12, end) infinite;
background-size: 100%;
}
@keyframes uni-loading {
0% {
transform: rotate3d(0, 0, 1, 0deg);
}
100% {
transform: rotate3d(0, 0, 1, 360deg);
}
}
@media (prefers-color-scheme: dark) {
html {
--UI-BG-CLOLOR-ACTIVE: #373737;
--UI-BORDER-CLOLOR-1: #373737;
/* UI */
--UI-BG: #000;
--UI-BG-0: #191919;
--UI-BG-1: #1f1f1f;
--UI-BG-2: #232323;
--UI-BG-3: #2f2f2f;
--UI-BG-4: #606060;
--UI-BG-5: #2c2c2c;
--UI-FG: #fff;
--UI-FG-0: hsla(0, 0%, 100%, 0.8);
--UI-FG-HALF: hsla(0, 0%, 100%, 0.6);
--UI-FG-1: hsla(0, 0%, 100%, 0.5);
--UI-FG-2: hsla(0, 0%, 100%, 0.3);
--UI-FG-3: hsla(0, 0%, 100%, 0.05);
}
body {
background-color: var(--UI-BG-0);
color: var(--UI-FG-0);
}
}

View File

@@ -0,0 +1,31 @@
uni-live-pusher {
width: 320px;
height: 240px;
display: inline-block;
line-height: 0;
overflow: hidden;
position: relative;
}
uni-live-pusher[hidden] {
display: none;
}
.uni-live-pusher-container {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
overflow: hidden;
background-color: black;
}
.uni-live-pusher-slot {
position: absolute;
top: 0;
width: 100%;
height: 100%;
overflow: hidden;
pointer-events: none;
}

View File

@@ -0,0 +1,31 @@
uni-map {
width: 300px;
height: 225px;
display: inline-block;
line-height: 0;
overflow: hidden;
position: relative;
}
uni-map[hidden] {
display: none;
}
.uni-map-container {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
overflow: hidden;
background-color: transparent;
}
.uni-map-slot {
position: absolute;
top: 0;
width: 100%;
height: 100%;
overflow: hidden;
pointer-events: none;
}

View File

@@ -0,0 +1,31 @@
uni-video {
width: 300px;
height: 225px;
display: inline-block;
line-height: 0;
overflow: hidden;
position: relative;
}
uni-video[hidden] {
display: none;
}
.uni-video-container {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
overflow: hidden;
background-color: black;
}
.uni-video-slot {
position: absolute;
top: 0;
width: 100%;
height: 100%;
overflow: hidden;
pointer-events: none;
}

View File

@@ -0,0 +1,8 @@
uni-web-view {
display: inline-block;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
}

View File

@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,4 @@
declare const _default: () => import("vite").Plugin[];
export default _default;
export { genClassName } from './plugins/utils';
export { transformVue } from './plugins/uvue/index';

View File

@@ -0,0 +1,32 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformVue = exports.genClassName = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const plugins_1 = require("./plugins");
const css_1 = require("./plugins/css");
const mainUTS_1 = require("./plugins/mainUTS");
const manifestJson_1 = require("./plugins/manifestJson");
const pagesJson_1 = require("./plugins/pagesJson");
const pre_1 = require("./plugins/pre");
const uvue_1 = require("./plugins/uvue");
const unicloud_1 = require("./plugins/unicloud");
exports.default = () => {
return [
(0, pre_1.uniPrePlugin)(),
(0, uni_cli_shared_1.uniUTSAppPlugin)({
x: true,
extApis: (0, uni_cli_shared_1.parseUniExtApiNamespacesOnce)(process.env.UNI_UTS_PLATFORM, process.env.UNI_UTS_TARGET_LANGUAGE),
}),
(0, plugins_1.uniAppUTSPlugin)(),
(0, mainUTS_1.uniAppMainPlugin)(),
(0, manifestJson_1.uniAppManifestPlugin)(),
(0, pagesJson_1.uniAppPagesPlugin)(),
(0, css_1.uniAppCssPlugin)(),
(0, uvue_1.uniAppUVuePlugin)(),
(0, unicloud_1.uniCloudPlugin)(),
];
};
var utils_1 = require("./plugins/utils");
Object.defineProperty(exports, "genClassName", { enumerable: true, get: function () { return utils_1.genClassName; } });
var index_1 = require("./plugins/uvue/index");
Object.defineProperty(exports, "transformVue", { enumerable: true, get: function () { return index_1.transformVue; } });

View File

@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function uniAppCssPlugin(): Plugin;

View File

@@ -0,0 +1,103 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniAppCssPlugin = void 0;
const path_1 = __importDefault(require("path"));
const picocolors_1 = __importDefault(require("picocolors"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const uni_nvue_styler_1 = require("@dcloudio/uni-nvue-styler");
const utils_1 = require("./utils");
function uniAppCssPlugin() {
const mainUTS = (0, uni_cli_shared_1.resolveMainPathOnce)(process.env.UNI_INPUT_DIR);
let resolvedConfig;
const name = 'uni:app-uvue-css';
return {
name,
apply: 'build',
configResolved(config) {
resolvedConfig = config;
const uvueCssPostPlugin = (0, uni_cli_shared_1.cssPostPlugin)(config, {
isJsCode: true,
platform: process.env.UNI_PLATFORM,
includeComponentCss: false,
chunkCssFilename(id) {
if (id === mainUTS) {
return 'App.style.uts';
}
const { filename } = (0, uni_cli_shared_1.parseVueRequest)(id);
if ((0, utils_1.isVue)(filename)) {
return (0, uni_cli_shared_1.normalizeNodeModules)(path_1.default.relative(process.env.UNI_INPUT_DIR, filename) + '.style.uts');
}
},
async chunkCssCode(filename, cssCode) {
cssCode = (0, uni_cli_shared_1.parseAssets)(resolvedConfig, cssCode);
const { code, messages } = await (0, uni_nvue_styler_1.parse)(cssCode, {
filename,
logLevel: 'ERROR',
mapOf: true,
chunk: 100,
type: 'uvue',
platform: process.env.UNI_UTS_PLATFORM,
});
messages.forEach((message) => {
if (message.type === 'error') {
let msg = `[plugin:uni:app-uvue-css] ${message.text}`;
if (message.line && message.column) {
msg += `\n${(0, uni_cli_shared_1.generateCodeFrame)(cssCode, {
line: message.line,
column: message.column,
}).replace(/\t/g, ' ')}`;
}
msg += `\n${(0, uni_cli_shared_1.formatAtFilename)(filename)}`;
resolvedConfig.logger.error(picocolors_1.default.red(msg));
}
});
return `export const ${(0, utils_1.genClassName)(filename.replace('.style.uts', ''))}Styles = ${code}`;
},
});
// 增加 css plugins
(0, uni_cli_shared_1.insertBeforePlugin)((0, uni_cli_shared_1.cssPlugin)(config), name, config);
const plugins = config.plugins;
const index = plugins.findIndex((p) => p.name === 'uni:app-uvue');
plugins.splice(index, 0, uvueCssPostPlugin);
},
async transform(source, filename) {
if (!uni_cli_shared_1.cssLangRE.test(filename) || uni_cli_shared_1.commonjsProxyRE.test(filename)) {
return;
}
if (source.includes('#endif')) {
source = (0, uni_cli_shared_1.preUVueCss)(source);
}
source = (0, uni_cli_shared_1.parseAssets)(resolvedConfig, source);
// 仅做校验使用
const { messages } = await (0, uni_nvue_styler_1.parse)(source, {
filename,
logLevel: 'WARNING',
map: true,
ts: true,
noCode: true,
type: 'uvue',
platform: process.env.UNI_UTS_PLATFORM,
});
messages.forEach((message) => {
if (message.type === 'warning') {
// 拆分成多行,第一行输出信息(有颜色),后续输出错误代码+文件行号
resolvedConfig.logger.warn(picocolors_1.default.yellow(`[plugin:uni:app-uvue-css] ${message.text}`));
let msg = '';
if (message.line && message.column) {
msg += `\n${(0, uni_cli_shared_1.generateCodeFrame)(source, {
line: message.line,
column: message.column,
}).replace(/\t/g, ' ')}\n`;
}
msg += `${(0, uni_cli_shared_1.formatAtFilename)(filename)}`;
resolvedConfig.logger.warn(msg);
}
});
return { code: source };
},
};
}
exports.uniAppCssPlugin = uniAppCssPlugin;

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,116 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const os_1 = __importDefault(require("os"));
const https_1 = __importDefault(require("https"));
const crypto_1 = __importDefault(require("crypto"));
const SERVER_HOST = 'uacer.dcloud.net.cn';
const SERVER_PATH = '/http/error-report-x';
const EXCLUDE_ERROR_LIST = [
'uni-app-compiler',
'Error: ENOENT: no such file or directory',
];
function getMacHash() {
let mac = '';
const network = os_1.default.networkInterfaces();
for (const key in network) {
const array = network[key];
for (let i = 0; i < array.length; i++) {
const item = array[i];
if (!item.family || (item.mac && item.mac === '00:00:00:00:00:00')) {
continue;
}
if (
// Node < v18
typeof item.family === 'string' &&
(item.family === 'IPv4' || item.family === 'IPv6')) {
mac = item.mac;
break;
}
else if (
// Node >= v18
typeof item.family === 'number' &&
(item.family === 4 || item.family === 6)) {
mac = item.mac;
break;
}
}
}
return crypto_1.default.createHash('md5').update(mac).digest('hex');
}
const CacheList = [];
function shouldReport(err = '') {
try {
const errMsg = err.toString();
const errorIndex = EXCLUDE_ERROR_LIST.findIndex((item) => errMsg.includes(item));
if (errorIndex >= 0) {
return false;
}
// 目前简单的上报逻辑为:错误信息中包含@dcloudio包名
if (errMsg.includes('@dcloudio') &&
!errMsg.includes('Errors compiling template')) {
return true;
}
}
catch (e) { }
return false;
}
function report(type, err) {
if (!shouldReport(err)) {
return;
}
if (typeof err === 'object') {
try {
err = err.toString();
}
catch (e) { }
}
const UNI_INPUT_DIR_REG = new RegExp(process.env.UNI_INPUT_DIR, 'ig');
const UNI_CLI_CONTEXT_REG = new RegExp(process.env.UNI_CLI_CONTEXT, 'ig');
err = err.replace(UNI_INPUT_DIR_REG, 'UNI_INPUT_DIR');
err = err.replace(UNI_CLI_CONTEXT_REG, 'UNI_CLI_CONTEXT');
const data = JSON.stringify({
di: getMacHash(),
np: process.platform,
nv: process.version,
cp: process.env.UNI_PLATFORM,
cv: process.env.UNI_COMPILER_VERSION,
hx: process.env.UNI_COMPILER_VERSION_TYPE,
et: type,
em: err,
});
const dataHash = crypto_1.default.createHash('md5').update(data).digest('hex');
if (CacheList.includes(dataHash)) {
return;
}
CacheList.push(dataHash);
setTimeout(() => {
const req = https_1.default.request({
hostname: SERVER_HOST,
port: 443,
path: SERVER_PATH,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length,
},
});
req.write(data);
req.end();
}, 10);
}
// @ts-ignore
global.__error_reporting__ = report;
process
.on('unhandledRejection', (reason, p) => {
// @ts-ignore
global.__error_reporting__('unhandledRejection', reason);
console.log(reason);
})
.on('uncaughtException', (err) => {
// @ts-ignore
global.__error_reporting__('uncaughtException', err.stack);
console.log(err);
});

View File

@@ -0,0 +1,2 @@
import { UniVitePlugin } from '@dcloudio/uni-cli-shared';
export declare function uniAppUTSPlugin(): UniVitePlugin;

View File

@@ -0,0 +1,287 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniAppUTSPlugin = void 0;
const path_1 = __importDefault(require("path"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const uni_i18n_1 = require("@dcloudio/uni-i18n");
const utils_1 = require("./utils");
const manifestJson_1 = require("./manifestJson");
Promise.resolve().then(() => __importStar(require('./errorReporting')));
const uniCloudSpaceList = (0, utils_1.getUniCloudSpaceList)();
const REMOVED_PLUGINS = [
'vite:build-metadata',
'vite:modulepreload-polyfill',
'vite:css',
'vite:esbuild',
'vite:wasm-helper',
'vite:worker',
// 'vite:asset', // replace
'vite:wasm-fallback',
'vite:define',
'vite:css-post',
'vite:build-html',
'vite:html-inline-proxy',
'vite:worker-import-meta-url',
'vite:asset-import-meta-url',
'vite:force-systemjs-wrap-complete',
'vite:watch-package-data',
'commonjs',
'vite:data-uri',
'vite:dynamic-import-vars',
'vite:import-glob',
'vite:build-import-analysis',
'vite:esbuild-transpile',
'vite:terser',
'vite:reporter',
];
let isFirst = true;
function uniAppUTSPlugin() {
const inputDir = process.env.UNI_INPUT_DIR;
const outputDir = process.env.UNI_OUTPUT_DIR;
const mainUTS = (0, uni_cli_shared_1.resolveMainPathOnce)(inputDir);
const tempOutputDir = (0, utils_1.uvueOutDir)();
const manifestJson = (0, uni_cli_shared_1.parseManifestJsonOnce)(inputDir);
// 预留一个口子,方便切换测试
const split = manifestJson['uni-app-x']?.split;
// 开始编译时,清空输出目录
function emptyOutDir() {
if (fs_extra_1.default.existsSync(outputDir)) {
(0, uni_cli_shared_1.emptyDir)(outputDir);
}
}
emptyOutDir();
return {
name: 'uni:app-uts',
apply: 'build',
uni: createUniOptions(),
config() {
return {
base: '/',
build: {
outDir: tempOutputDir,
lib: {
// 必须使用 lib 模式
fileName: 'output',
entry: (0, uni_cli_shared_1.resolveMainPathOnce)(inputDir),
formats: ['cjs'],
},
rollupOptions: {
external(source) {
if (['vue', 'vuex', 'pinia'].includes(source)) {
return true;
}
// 相对目录
if (source.startsWith('@/') || source.startsWith('.')) {
return false;
}
if (path_1.default.isAbsolute(source)) {
return false;
}
// android 系统库,三方库
if (source.includes('.')) {
return true;
}
return false;
},
output: {
chunkFileNames(chunk) {
// if (chunk.isDynamicEntry && chunk.facadeModuleId) {
// const { filename } = parseVueRequest(chunk.facadeModuleId)
// if (filename.endsWith('.nvue')) {
// return (
// removeExt(
// normalizePath(path.relative(inputDir, filename))
// ) + '.js'
// )
// }
// }
return '[name].js';
},
},
},
},
};
},
configResolved(config) {
const plugins = config.plugins;
const len = plugins.length;
for (let i = len - 1; i >= 0; i--) {
const plugin = plugins[i];
if (REMOVED_PLUGINS.includes(plugin.name)) {
plugins.splice(i, 1);
}
}
// 强制不inline
config.build.assetsInlineLimit = 0;
(0, uni_cli_shared_1.injectAssetPlugin)(config, { isAppX: true });
},
async transform(code, id) {
const { filename } = (0, uni_cli_shared_1.parseVueRequest)(id);
if (!filename.endsWith('.uts')) {
return;
}
// 仅处理 uts 文件
// 忽略 uni-app-uts/lib/automator/index.uts
if (!filename.includes('uni-app-uts')) {
const isMainUTS = (0, uni_cli_shared_1.normalizePath)(id) === mainUTS;
const fileName = path_1.default.relative(inputDir, id);
this.emitFile({
type: 'asset',
fileName: normalizeFilename(fileName, isMainUTS),
source: normalizeCode(code, isMainUTS),
});
}
code = await (0, utils_1.parseImports)(code);
return code;
},
async writeBundle() {
let pageCount = 0;
if (isFirst) {
pageCount = parseInt(process.env.UNI_APP_X_PAGE_COUNT) || 0;
isFirst = false;
}
const res = await (0, uni_cli_shared_1.resolveUTSCompiler)().compileApp(path_1.default.join(tempOutputDir, 'index.uts'), {
pageCount,
uniCloudObjectInfo: (0, utils_1.getUniCloudObjectInfo)(uniCloudSpaceList),
split: split !== false,
disableSplitManifest: process.env.NODE_ENV !== 'development',
inputDir: tempOutputDir,
outputDir: outputDir,
package: 'uni.' + (manifestJson.appid || utils_1.DEFAULT_APPID).replace(/_/g, ''),
sourceMap: process.env.NODE_ENV === 'development',
uni_modules: [...uni_cli_shared_1.utsPlugins],
extApis: (0, uni_cli_shared_1.parseUniExtApiNamespacesOnce)(process.env.UNI_UTS_PLATFORM, process.env.UNI_UTS_TARGET_LANGUAGE),
extApiComponents: [...(0, utils_1.getExtApiComponents)()],
uvueClassNamePrefix: utils_1.UVUE_CLASS_NAME_PREFIX,
});
if (res) {
if (process.env.NODE_ENV === 'development') {
const files = [];
if (process.env.UNI_APP_UTS_CHANGED_FILES) {
try {
files.push(...JSON.parse(process.env.UNI_APP_UTS_CHANGED_FILES));
}
catch (e) { }
}
if (res.changed) {
// 触发了kotlinc编译且没有编译成功
if (!res.changed.length && res.kotlinc) {
throw new Error('编译失败');
}
files.push(...res.changed);
}
process.env.UNI_APP_UTS_CHANGED_FILES = JSON.stringify([
...new Set(files),
]);
}
else {
// 生产环境记录使用到的modules
const modules = res.inject_modules;
const manifest = (0, manifestJson_1.getOutputManifestJson)();
if (manifest) {
// 执行了摇树逻辑,就需要设置 modules 节点
const app = manifest.app;
if (!app.distribute) {
app.distribute = {};
}
if (!app.distribute.modules) {
app.distribute.modules = {};
}
if (modules) {
modules.forEach((name) => {
app.distribute.modules[name] = {};
});
}
fs_extra_1.default.outputFileSync(path_1.default.resolve(process.env.UNI_OUTPUT_DIR, 'manifest.json'), JSON.stringify(manifest, null, 2));
}
}
}
},
};
}
exports.uniAppUTSPlugin = uniAppUTSPlugin;
function normalizeFilename(filename, isMain = false) {
if (isMain) {
return 'index.uts';
}
return (0, utils_1.parseUTSRelativeFilename)(filename);
}
function normalizeCode(code, isMain = false) {
if (!isMain) {
return code;
}
const automatorCode = process.env.UNI_AUTOMATOR_WS_ENDPOINT
? 'initAutomator();'
: '';
return `
${code}
export function main(app: IApp) {
defineAppConfig();
definePageRoutes();
${automatorCode}
(createApp()['app'] as VueApp).mount(app);
}
`;
}
function createUniOptions() {
return {
copyOptions() {
const platform = process.env.UNI_PLATFORM;
const inputDir = process.env.UNI_INPUT_DIR;
const outputDir = process.env.UNI_OUTPUT_DIR;
const targets = [];
// 自动化测试时,不启用隐私政策
if (!process.env.UNI_AUTOMATOR_WS_ENDPOINT) {
targets.push({
src: 'androidPrivacy.json',
dest: outputDir,
transform(source) {
const options = (0, uni_cli_shared_1.initI18nOptions)(platform, inputDir, false, true);
if (!options) {
return;
}
return (0, uni_i18n_1.compileI18nJsonStr)(source.toString(), options);
},
});
const debugFilename = '__nvue_debug__';
if (fs_extra_1.default.existsSync(path_1.default.resolve(inputDir, debugFilename))) {
targets.push({
src: debugFilename,
dest: outputDir,
});
}
}
return {
assets: ['hybrid/html/**/*', 'uni_modules/*/hybrid/html/**/*'],
targets,
};
},
};
}

View File

@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function uniAppMainPlugin(): Plugin;

View File

@@ -0,0 +1,24 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniAppMainPlugin = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const utils_1 = require("./utils");
function uniAppMainPlugin() {
const mainUTS = (0, uni_cli_shared_1.resolveMainPathOnce)(process.env.UNI_INPUT_DIR);
return {
name: 'uni:app-main',
apply: 'build',
async transform(code, id) {
if ((0, uni_cli_shared_1.normalizePath)(id) === mainUTS) {
code = await (0, utils_1.parseImports)(code);
return `
import './${uni_cli_shared_1.MANIFEST_JSON_UTS}'
import './${uni_cli_shared_1.PAGES_JSON_UTS}'
${code}
export default 'main.uts'
`;
}
},
};
}
exports.uniAppMainPlugin = uniAppMainPlugin;

View File

@@ -0,0 +1,3 @@
import type { Plugin } from 'vite';
export declare function getOutputManifestJson(): Record<string, any> | undefined;
export declare function uniAppManifestPlugin(): Plugin;

View File

@@ -0,0 +1,87 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniAppManifestPlugin = exports.getOutputManifestJson = void 0;
const path_1 = __importDefault(require("path"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const utils_1 = require("./utils");
function isManifest(id) {
return id.endsWith(uni_cli_shared_1.MANIFEST_JSON_UTS);
}
let outputManifestJson = undefined;
function getOutputManifestJson() {
return outputManifestJson;
}
exports.getOutputManifestJson = getOutputManifestJson;
function uniAppManifestPlugin() {
const manifestJsonPath = path_1.default.resolve(process.env.UNI_INPUT_DIR, 'manifest.json');
const manifestJsonUTSPath = path_1.default.resolve(process.env.UNI_INPUT_DIR, uni_cli_shared_1.MANIFEST_JSON_UTS);
let manifestJson = {};
return {
name: 'uni:app-manifest',
apply: 'build',
resolveId(id) {
if (isManifest(id)) {
return manifestJsonUTSPath;
}
},
load(id) {
if (isManifest(id)) {
return fs_extra_1.default.readFileSync(manifestJsonPath, 'utf8');
}
},
transform(code, id) {
if (isManifest(id)) {
this.addWatchFile(path_1.default.resolve(process.env.UNI_INPUT_DIR, 'manifest.json'));
manifestJson = (0, uni_cli_shared_1.parseJson)(code);
return `export default 'manifest.json'`;
}
},
generateBundle(_, bundle) {
if (bundle[utils_1.ENTRY_FILENAME]) {
const asset = bundle[utils_1.ENTRY_FILENAME];
const singleThread = manifestJson?.['uni-app-x']?.['singleThread'] === true
? `override singleThread: Boolean = true`
: '';
asset.source =
asset.source +
`
import { AppConfig } from "io.dcloud.uniapp.appframe"
export class UniAppConfig extends AppConfig {
override name: string = "${manifestJson.name || ''}"
override appid: string = "${manifestJson.appid || ''}"
override versionName: string = "${manifestJson.versionName || ''}"
override versionCode: string = "${manifestJson.versionCode || ''}"
override uniCompileVersion: string = "${process.env.UNI_COMPILER_VERSION || ''}"
// override tabBar = __uniTabBar
// override launchPage = __uniLaunchPage
${singleThread}
constructor() {}
}
`;
}
},
writeBundle() {
const app = manifestJson.app || {};
outputManifestJson = {
id: manifestJson.appid || '',
name: manifestJson.name || '',
description: manifestJson.description || '',
version: {
name: manifestJson.versionName || '',
code: manifestJson.versionCode || '',
},
'uni-app-x': manifestJson['uni-app-x'] || {},
app,
};
if (process.env.NODE_ENV !== 'production') {
// 发行模式下需要等解析ext-api模块
fs_extra_1.default.outputFileSync(path_1.default.resolve(process.env.UNI_OUTPUT_DIR, 'manifest.json'), JSON.stringify(outputManifestJson, null, 2));
}
},
};
}
exports.uniAppManifestPlugin = uniAppManifestPlugin;

View File

@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function uniAppPagesPlugin(): Plugin;

View File

@@ -0,0 +1,112 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniAppPagesPlugin = void 0;
const path_1 = __importDefault(require("path"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const utils_1 = require("./utils");
function isPages(id) {
return id.endsWith(uni_cli_shared_1.PAGES_JSON_UTS);
}
function uniAppPagesPlugin() {
const pagesJsonPath = path_1.default.resolve(process.env.UNI_INPUT_DIR, 'pages.json');
const pagesJsonUTSPath = path_1.default.resolve(process.env.UNI_INPUT_DIR, uni_cli_shared_1.PAGES_JSON_UTS);
let imports = [];
let routes = [];
let globalStyle = 'new Map()';
let tabBar = 'null';
let launchPage = 'null';
let conditionUrl = '';
let uniIdRouter = 'new Map()';
return {
name: 'uni:app-pages',
apply: 'build',
resolveId(id) {
if (isPages(id)) {
return pagesJsonUTSPath;
}
},
load(id) {
if (isPages(id)) {
return fs_extra_1.default.readFileSync(pagesJsonPath, 'utf8');
}
},
transform(code, id) {
if (isPages(id)) {
this.addWatchFile(path_1.default.resolve(process.env.UNI_INPUT_DIR, 'pages.json'));
const pagesJson = (0, uni_cli_shared_1.normalizeUniAppXAppPagesJson)(code);
imports = [];
routes = [];
process.env.UNI_APP_X_PAGE_COUNT = pagesJson.pages.length + '';
pagesJson.pages.forEach((page, index) => {
const className = (0, utils_1.genClassName)(page.path);
let isQuit = index === 0;
imports.push(page.path);
routes.push(`{ path: "${page.path}", component: ${className}Class, meta: { isQuit: ${isQuit} } as PageMeta, style: ${stringifyPageStyle(page.style)}${page.needLogin === undefined
? ''
: ', needLogin: ' + page.needLogin} } as PageRoute`);
});
if (pagesJson.globalStyle) {
globalStyle = stringifyPageStyle(pagesJson.globalStyle);
}
if (pagesJson.tabBar) {
tabBar = (0, utils_1.stringifyMap)(pagesJson.tabBar);
}
if (pagesJson.condition) {
const conditionInfo = (0, uni_cli_shared_1.parseArguments)(pagesJson);
if (conditionInfo) {
const { path, query } = JSON.parse(conditionInfo);
conditionUrl = `${path}${query ? '?' + query : ''}`;
}
}
if (pagesJson.uniIdRouter) {
uniIdRouter = (0, utils_1.stringifyMap)(pagesJson.uniIdRouter);
}
launchPage = stringifyLaunchPage(pagesJson.pages[0]);
return `${imports.map((p) => `import './${p}.uvue'`).join('\n')}
export default 'pages.json'`;
}
},
generateBundle(_, bundle) {
if (bundle[utils_1.ENTRY_FILENAME]) {
const asset = bundle[utils_1.ENTRY_FILENAME];
asset.source =
asset.source +
`
${imports
.map((p) => {
const className = (0, utils_1.genClassName)(p);
return `import ${className}Class from './${p}.uvue?type=page'`;
})
.join('\n')}
function definePageRoutes() {
${routes.map((route) => `__uniRoutes.push(${route})`).join('\n')}
}
const __uniTabBar: Map<string, any | null> | null = ${tabBar}
const __uniLaunchPage: Map<string, any | null> = ${launchPage}
@Suppress("UNCHECKED_CAST")
function defineAppConfig(){
__uniConfig.entryPagePath = '/${imports[0]}'
__uniConfig.globalStyle = ${globalStyle}
__uniConfig.tabBar = __uniTabBar as Map<string, any> | null
__uniConfig.conditionUrl = '${conditionUrl}'
__uniConfig.uniIdRouter = ${uniIdRouter}
}
`;
}
},
};
}
exports.uniAppPagesPlugin = uniAppPagesPlugin;
function stringifyLaunchPage(launchPage) {
return (0, utils_1.stringifyMap)({
url: launchPage.path,
style: launchPage.style,
}, true);
}
function stringifyPageStyle(pageStyle) {
return (0, utils_1.stringifyMap)(pageStyle);
}

View File

@@ -0,0 +1,7 @@
import { Plugin } from 'vite';
import { FilterPattern } from '@rollup/pluginutils';
export interface UniPrePluginOptions {
include?: FilterPattern;
exclude?: FilterPattern;
}
export declare function uniPrePlugin(options?: UniPrePluginOptions): Plugin;

View File

@@ -0,0 +1,52 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniPrePlugin = void 0;
const path_1 = __importDefault(require("path"));
const debug_1 = __importDefault(require("debug"));
const pluginutils_1 = require("@rollup/pluginutils");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const debugPreJs = (0, debug_1.default)('uni:pre-js');
const debugPreHtml = (0, debug_1.default)('uni:pre-html');
const debugPreJsTry = (0, debug_1.default)('uni:pre-js-try');
const PRE_HTML_EXTNAME = ['.vue', '.uvue'];
const PRE_JS_EXTNAME = ['.json', '.css', '.uts'].concat(PRE_HTML_EXTNAME);
function uniPrePlugin(options = {}) {
const filter = (0, pluginutils_1.createFilter)(options.include, options.exclude);
const preJsFile = uni_cli_shared_1.preUVueJs;
const preHtmlFile = uni_cli_shared_1.preUVueHtml;
return {
name: 'uni:pre',
transform(code, id) {
if (!filter(id)) {
return;
}
const { filename } = (0, uni_cli_shared_1.parseVueRequest)(id);
const extname = path_1.default.extname(filename);
const isHtml = PRE_HTML_EXTNAME.includes(extname);
const isJs = PRE_JS_EXTNAME.includes(extname);
const isPre = isHtml || isJs;
if (isPre) {
debugPreJsTry(id);
}
const hasEndif = isPre && code.includes('#endif');
if (!hasEndif) {
return;
}
if (isHtml) {
code = preHtmlFile(code);
debugPreHtml(id);
}
if (isJs) {
code = preJsFile(code);
debugPreJs(id);
}
return {
code,
};
},
};
}
exports.uniPrePlugin = uniPrePlugin;

View File

@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function uniCloudPlugin(): Plugin;

View File

@@ -0,0 +1,37 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniCloudPlugin = void 0;
const utils_1 = require("./utils");
const uniCloudSpaceList = (0, utils_1.getUniCloudSpaceList)();
function uniCloudPlugin() {
return {
name: 'uni:app-unicloud',
apply: 'build',
generateBundle(_, bundle) {
if (uniCloudSpaceList.length === 0) {
return;
}
if (bundle[utils_1.ENTRY_FILENAME]) {
const asset = bundle[utils_1.ENTRY_FILENAME];
asset.source =
asset.source +
`
import "io.dcloud.unicloud.InternalUniCloudConfig"
export class UniCloudConfig extends InternalUniCloudConfig {
override isDev : boolean = ${process.env.NODE_ENV === 'development' ? 'true' : 'false'}
override spaceList : string = ${JSON.stringify(JSON.stringify(uniCloudSpaceList.map((item) => {
const itemCopy = { ...item };
delete itemCopy.workspaceFolder;
return itemCopy;
})))}
override debuggerInfo ?: string = ${JSON.stringify(process.env.UNICLOUD_DEBUG || null)}
override secureNetworkEnable : boolean = false
override secureNetworkConfig ?: string = ""
constructor() {}
}
`;
}
},
};
}
exports.uniCloudPlugin = uniCloudPlugin;

View File

@@ -0,0 +1,28 @@
export declare const UVUE_CLASS_NAME_PREFIX = "Gen";
export declare const DEFAULT_APPID = "HBuilder";
export declare const ENTRY_FILENAME = "index.uts";
export declare function parseImports(code: string): Promise<string>;
export declare function kotlinOutDir(): string;
export declare function uvueOutDir(): string;
export declare function isVue(filename: string): boolean;
export declare function stringifyMap(obj: unknown, ts?: boolean): string;
export declare function parseUTSRelativeFilename(filename: string): string;
export declare function parseUTSImportFilename(filename: string): string;
type UniCloudSpace = {
provider: string;
spaceName: string;
spaceId: string;
clientSecret?: string;
endpoint?: string;
workspaceFolder?: string;
};
export declare function getUniCloudSpaceList(): Array<UniCloudSpace>;
type UniCloudObjectInfo = {
name: string;
methodList: string[];
};
export declare function getUniCloudObjectInfo(uniCloudSpaceList: Array<UniCloudSpace>): Array<UniCloudObjectInfo>;
export declare function addExtApiComponents(components: string[]): void;
export declare function getExtApiComponents(): Set<string>;
export declare function genClassName(fileName: string, prefix?: string): string;
export {};

View File

@@ -0,0 +1,211 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.genClassName = exports.getExtApiComponents = exports.addExtApiComponents = exports.getUniCloudObjectInfo = exports.getUniCloudSpaceList = exports.parseUTSImportFilename = exports.parseUTSRelativeFilename = exports.stringifyMap = exports.isVue = exports.uvueOutDir = exports.kotlinOutDir = exports.parseImports = exports.ENTRY_FILENAME = exports.DEFAULT_APPID = exports.UVUE_CLASS_NAME_PREFIX = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const es_module_lexer_1 = require("es-module-lexer");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const shared_1 = require("@vue/shared");
exports.UVUE_CLASS_NAME_PREFIX = 'Gen';
exports.DEFAULT_APPID = 'HBuilder';
exports.ENTRY_FILENAME = 'index.uts';
async function parseImports(code) {
await es_module_lexer_1.init;
const [imports] = (0, es_module_lexer_1.parse)(code);
return imports
.map(({ s, e }) => {
return `import "${code.slice(s, e)}"`;
})
.concat(parseUniExtApiImports(code))
.join('\n');
}
exports.parseImports = parseImports;
function parseUniExtApiImports(code) {
const extApis = (0, uni_cli_shared_1.parseUniExtApiNamespacesJsOnce)(process.env.UNI_UTS_PLATFORM, process.env.UNI_UTS_TARGET_LANGUAGE);
const pattern = /uni\.(\w+)/g;
const apis = new Set();
let match;
while ((match = pattern.exec(code)) !== null) {
apis.add(match[1]);
}
const imports = [];
apis.forEach((api) => {
const extApi = extApis[api];
if (extApi) {
imports.push(`import "${extApi[0]}"`);
}
});
return imports;
}
function kotlinOutDir() {
return path_1.default.join(process.env.UNI_OUTPUT_DIR, '../.kotlin');
}
exports.kotlinOutDir = kotlinOutDir;
function uvueOutDir() {
return path_1.default.join(process.env.UNI_OUTPUT_DIR, '../.uvue');
}
exports.uvueOutDir = uvueOutDir;
function isVue(filename) {
return filename.endsWith('.vue') || filename.endsWith('.uvue');
}
exports.isVue = isVue;
function stringifyMap(obj, ts = false) {
return serialize(obj, ts);
}
exports.stringifyMap = stringifyMap;
function serialize(obj, ts = false) {
if ((0, shared_1.isString)(obj)) {
return `"${obj}"`;
}
else if ((0, shared_1.isPlainObject)(obj)) {
const entries = Object.entries(obj).map(([key, value]) => `[${serialize(key, ts)},${serialize(value, ts)}]`);
if (entries.length) {
return `utsMapOf([${entries.join(',')}])`;
}
if (ts) {
return `utsMapOf<string, any | null>()`;
}
return `utsMapOf()`;
}
else if ((0, shared_1.isArray)(obj)) {
return `[${obj.map((item) => serialize(item, ts)).join(',')}]`;
}
else {
return String(obj);
}
}
function parseUTSRelativeFilename(filename) {
if (!path_1.default.isAbsolute(filename)) {
return filename;
}
return (0, uni_cli_shared_1.normalizeNodeModules)(path_1.default.relative(process.env.UNI_INPUT_DIR, filename));
}
exports.parseUTSRelativeFilename = parseUTSRelativeFilename;
function parseUTSImportFilename(filename) {
if (!path_1.default.isAbsolute(filename)) {
return filename;
}
return (0, uni_cli_shared_1.normalizePath)(path_1.default.join(uvueOutDir(), (0, uni_cli_shared_1.normalizeNodeModules)(path_1.default.relative(process.env.UNI_INPUT_DIR, filename))));
}
exports.parseUTSImportFilename = parseUTSImportFilename;
let uniCloudSpaceList;
function getUniCloudSpaceList() {
if (uniCloudSpaceList) {
return uniCloudSpaceList;
}
if (!process.env.UNI_CLOUD_SPACES) {
uniCloudSpaceList = [];
return uniCloudSpaceList;
}
try {
const spaces = JSON.parse(process.env.UNI_CLOUD_SPACES);
if (!Array.isArray(spaces)) {
uniCloudSpaceList = [];
return uniCloudSpaceList;
}
uniCloudSpaceList = spaces.map((space) => {
if (space.provider === 'tcb') {
space.provider = 'tencent';
}
if (space.clientSecret) {
return {
provider: space.provider,
spaceName: space.name,
spaceId: space.id,
clientSecret: space.clientSecret,
endpoint: space.apiEndpoint,
workspaceFolder: space.workspaceFolder,
};
}
else {
return {
provider: space.provider,
spaceName: space.name,
spaceId: space.id,
workspaceFolder: space.workspaceFolder,
};
}
});
}
catch (e) {
console.error(e);
}
uniCloudSpaceList = uniCloudSpaceList || [];
if (uniCloudSpaceList.length > 1) {
console.warn('Multi uniCloud space is not supported yet.');
}
return uniCloudSpaceList;
}
exports.getUniCloudSpaceList = getUniCloudSpaceList;
function getUniCloudObjectInfo(uniCloudSpaceList) {
let uniCloudWorkspaceFolder = process.env.UNI_INPUT_DIR.endsWith('src')
? path_1.default.resolve(process.env.UNI_INPUT_DIR, '..')
: process.env.UNI_INPUT_DIR;
let serviceProvider = 'aliyun';
if (uniCloudSpaceList && uniCloudSpaceList.length > 0) {
const space = uniCloudSpaceList[0];
if (space.workspaceFolder) {
uniCloudWorkspaceFolder = space.workspaceFolder;
}
serviceProvider = space.provider === 'tencent' ? 'tcb' : space.provider;
}
else {
serviceProvider =
['aliyun', 'tcb', 'alipay'].find((item) => fs_1.default.existsSync(path_1.default.resolve(uniCloudWorkspaceFolder, 'uniCloud-' + item))) || 'aliyun';
}
try {
const { getWorkspaceObjectInfo } = require('../../lib/unicloud-utils');
return getWorkspaceObjectInfo(uniCloudWorkspaceFolder, serviceProvider);
}
catch (e) {
console.error(e);
return [];
}
}
exports.getUniCloudObjectInfo = getUniCloudObjectInfo;
const extApiComponents = new Set();
function addExtApiComponents(components) {
components.forEach((component) => {
extApiComponents.add(component);
});
}
exports.addExtApiComponents = addExtApiComponents;
function getExtApiComponents() {
return extApiComponents;
}
exports.getExtApiComponents = getExtApiComponents;
function genClassName(fileName, prefix = 'Gen') {
return (prefix +
(0, shared_1.capitalize)((0, shared_1.camelize)(verifySymbol((0, uni_cli_shared_1.removeExt)((0, uni_cli_shared_1.normalizeNodeModules)(fileName).replace(/[\/|_]/g, '-'))))));
}
exports.genClassName = genClassName;
function isValidStart(c) {
return !!c.match(/^[A-Za-z_-]$/);
}
function isValidContinue(c) {
return !!c.match(/^[A-Za-z0-9_-]$/);
}
function verifySymbol(s) {
const chars = Array.from(s);
if (isValidStart(chars[0]) && chars.slice(1).every(isValidContinue)) {
return s;
}
const buf = [];
let hasStart = false;
for (const c of chars) {
if (!hasStart && isValidStart(c)) {
hasStart = true;
buf.push(c);
}
else if (isValidContinue(c)) {
buf.push(c);
}
}
if (buf.length === 0) {
buf.push('_');
}
return buf.join('');
}

View File

@@ -0,0 +1,4 @@
import { SFCDescriptor } from '@vue/compiler-sfc';
export declare function genScript({ script }: SFCDescriptor, _options: {
filename: string;
}): string;

View File

@@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.genScript = void 0;
function genScript({ script }, _options) {
if (!script) {
return `
export default {}
`;
}
return ('\n'.repeat(script.loc.start.line - 1) +
`${script.content}
`);
}
exports.genScript = genScript;

View File

@@ -0,0 +1,12 @@
import type { SFCDescriptor } from '@vue/compiler-sfc';
import type { PluginContext, TransformPluginContext } from 'rollup';
import { ResolvedOptions } from '../descriptorCache';
export declare function genStyle(_: SFCDescriptor, { className }: {
className: string;
filename: string;
}): string;
export declare function genJsStylesCode(descriptor: SFCDescriptor, pluginContext: PluginContext): Promise<string>;
export declare function transformStyle(code: string, descriptor: SFCDescriptor, index: number, options: ResolvedOptions, pluginContext: TransformPluginContext, filename: string): Promise<{
code: string;
map: null;
} | null>;

View File

@@ -0,0 +1,90 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformStyle = exports.genJsStylesCode = exports.genStyle = void 0;
const descriptorCache_1 = require("../descriptorCache");
function genStyle(_, { className }) {
return `/*${className}Styles*/`;
}
exports.genStyle = genStyle;
async function genJsStylesCode(descriptor, pluginContext) {
let stylesCode = ``;
if (descriptor.styles.length) {
for (let i = 0; i < descriptor.styles.length; i++) {
const style = descriptor.styles[i];
if (style.src) {
await linkSrcToDescriptor(style.src, descriptor, pluginContext);
}
const src = style.src || descriptor.filename;
// do not include module in default query, since we use it to indicate
// that the module needs to export the modules json
const attrsQuery = attrsToQuery(style.attrs, 'css');
const srcQuery = style.src ? '&src=true' : '';
const query = `?vue&type=style&index=${i}${srcQuery}`;
const styleRequest = src + query + attrsQuery;
stylesCode += `\nimport ${JSON.stringify(styleRequest)}`;
}
}
return stylesCode;
}
exports.genJsStylesCode = genJsStylesCode;
/**
* For blocks with src imports, it is important to link the imported file
* with its owner SFC descriptor so that we can get the information about
* the owner SFC when compiling that file in the transform phase.
*/
async function linkSrcToDescriptor(src, descriptor, pluginContext) {
const srcFile = (await pluginContext.resolve(src, descriptor.filename))?.id || src;
// #1812 if the src points to a dep file, the resolved id may contain a
// version query.
(0, descriptorCache_1.setSrcDescriptor)(srcFile.replace(/\?.*$/, ''), descriptor);
}
// these are built-in query parameters so should be ignored
// if the user happen to add them as attrs
const ignoreList = ['id', 'index', 'src', 'type', 'lang', 'module', 'scoped'];
function attrsToQuery(attrs, langFallback, forceLangFallback = false) {
let query = ``;
for (const name in attrs) {
const value = attrs[name];
if (!ignoreList.includes(name)) {
query += `&${encodeURIComponent(name)}${value ? `=${encodeURIComponent(value)}` : ``}`;
}
}
if (langFallback || attrs.lang) {
query +=
`lang` in attrs
? forceLangFallback
? `&lang.${langFallback}`
: `&lang.${attrs.lang}`
: `&lang.${langFallback}`;
}
return query;
}
async function transformStyle(code, descriptor, index, options, pluginContext, filename) {
const block = descriptor.styles[index];
// vite already handles pre-processors and CSS module so this is only
// applying SFC-specific transforms like scoped mode and CSS vars rewrite (v-bind(var))
const result = await options.compiler.compileStyleAsync({
filename: descriptor.filename,
id: `data-v-${descriptor.id}`,
isProd: true,
source: code,
});
if (result.errors.length) {
result.errors.forEach((error) => {
if (error.line && error.column) {
error.loc = {
file: descriptor.filename,
line: error.line + block.loc.start.line,
column: error.column,
};
}
pluginContext.error(error);
});
return null;
}
return {
code: result.code,
map: null,
};
}
exports.transformStyle = transformStyle;

View File

@@ -0,0 +1,3 @@
import { SFCDescriptor } from '@vue/compiler-sfc';
import { CompilerOptions } from '../compiler/options';
export declare function genTemplate({ template }: SFCDescriptor, options: CompilerOptions): import("../compiler/options").CodegenResult;

View File

@@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.genTemplate = void 0;
const compiler_1 = require("../compiler");
const utils_1 = require("../compiler/utils");
function genTemplate({ template }, options) {
if (!template) {
return {
code: (0, utils_1.genRenderFunctionDecl)(options) + ` { return null }`,
importEasyComponents: [],
importUTSComponents: [],
elements: [],
};
}
return (0, compiler_1.compile)(template.content, options);
}
exports.genTemplate = genTemplate;

View File

@@ -0,0 +1,24 @@
import { SourceMapGenerator } from 'source-map-js';
import { JSChildNode, RootNode, SSRCodegenNode, TemplateChildNode } from '@vue/compiler-core';
import { ParserPlugin } from '@babel/parser';
import { CodegenOptions, CodegenResult } from './options';
type CodegenNode = TemplateChildNode | JSChildNode | SSRCodegenNode;
export interface CodegenContext extends Required<Omit<CodegenOptions, 'sourceMapGeneratedLine' | 'className'>> {
source: string;
code: string;
importEasyComponents: string[];
importUTSComponents: string[];
line: number;
column: number;
offset: number;
indentLevel: number;
map?: SourceMapGenerator;
expressionPlugins: ParserPlugin[];
helper(key: symbol): string;
push(code: string, node?: CodegenNode): void;
indent(): void;
deindent(withoutNewLine?: boolean): void;
newline(): void;
}
export declare function generate(ast: RootNode, options: CodegenOptions): CodegenResult;
export {};

View File

@@ -0,0 +1,589 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generate = void 0;
const source_map_js_1 = require("source-map-js");
const compiler_core_1 = require("@vue/compiler-core");
const shared_1 = require("@vue/shared");
const parser_1 = require("@babel/parser");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const utils_1 = require("./utils");
const runtimeHelpers_1 = require("./runtimeHelpers");
const transformExpression_1 = require("./transforms/transformExpression");
const types_1 = require("@babel/types");
const transformSlotPropsDestructuring_1 = require("./transforms/transformSlotPropsDestructuring");
function createCodegenContext(ast, { rootDir, targetLanguage, mode = 'default', prefixIdentifiers = false, bindingMetadata = {}, sourceMap = false, filename = '', matchEasyCom = shared_1.NOOP, parseUTSComponent = shared_1.NOOP, }) {
const context = {
rootDir,
targetLanguage,
mode,
prefixIdentifiers,
bindingMetadata,
sourceMap,
filename,
source: ast.loc.source,
code: ``,
importEasyComponents: [],
importUTSComponents: [],
column: 1,
line: 1,
offset: 0,
indentLevel: 0,
map: undefined,
expressionPlugins: ['typescript'],
matchEasyCom,
parseUTSComponent,
helper(key) {
return `${compiler_core_1.helperNameMap[key]}`;
},
push(code, node) {
context.code += code;
if (context.map) {
if (node) {
let name;
if (node.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
const content = node.content.replace(/^_ctx\./, '');
if (content !== node.content && (0, compiler_core_1.isSimpleIdentifier)(content)) {
name = content;
}
}
addMapping(node.loc.start, name);
}
(0, compiler_core_1.advancePositionWithMutation)(context, code);
if (node && node.loc !== compiler_core_1.locStub) {
addMapping(node.loc.end);
}
}
},
indent() {
newline(++context.indentLevel);
},
deindent(withoutNewLine = false) {
if (withoutNewLine) {
--context.indentLevel;
}
else {
newline(--context.indentLevel);
}
},
newline() {
newline(context.indentLevel);
},
};
function newline(n) {
context.push('\n' + ` `.repeat(n));
}
function addMapping(loc, name) {
context.map.addMapping({
name,
source: context.filename,
original: {
line: loc.line,
column: loc.column - 1, // source-map column is 0 based
},
generated: {
line: context.line,
column: context.column - 1,
},
});
}
if (sourceMap) {
// lazy require source-map implementation, only in non-browser builds
context.map = new source_map_js_1.SourceMapGenerator();
context.map.setSourceContent(filename, context.source);
}
return context;
}
function generate(ast, options) {
const context = createCodegenContext(ast, options);
const { mode, deindent, indent, push, newline } = context;
if (mode === 'function') {
genEasyComImports(ast.components, context);
push((0, utils_1.genRenderFunctionDecl)(options) + ` {`);
newline();
push(`const _ctx = this`);
// generate asset resolution statements
if (ast.components.length) {
newline();
genAssets(ast.components, 'component', context);
if (ast.directives.length || ast.temps > 0) {
newline();
}
}
if (ast.directives.length) {
genAssets(ast.directives, 'directive', context);
if (ast.temps > 0) {
newline();
}
}
if (ast.components.length || ast.directives.length || ast.temps) {
newline();
}
indent();
push(`return `);
}
if (ast.codegenNode) {
genNode(ast.codegenNode, context);
}
else {
push(`null`);
}
if (mode === 'function') {
deindent();
push(`}`);
}
return {
code: context.code,
importEasyComponents: context.importEasyComponents,
importUTSComponents: context.importUTSComponents,
// SourceMapGenerator does have toJSON() method but it's not in the types
map: context.map ? context.map.toJSON() : undefined,
// @ts-ignore
elements: ast.elements,
};
}
exports.generate = generate;
function genEasyComImports(components, { push, newline, matchEasyCom, rootDir }) {
for (let i = 0; i < components.length; i++) {
let id = components[i];
const maybeSelfReference = id.endsWith('__self');
if (maybeSelfReference) {
id = id.slice(0, -6);
}
const source = matchEasyCom(id, true);
if (source) {
const componentId = (0, compiler_core_1.toValidAssetId)(id, 'easycom');
push(`import ${componentId}${(0, utils_1.genImportComponentPublicInstance)(rootDir, id, source)} from '${source}'`);
newline();
}
}
}
function genAssets(assets, type, { helper, push, newline, importEasyComponents, matchEasyCom, rootDir, }) {
const resolver = helper(type === 'component' ? runtimeHelpers_1.RESOLVE_COMPONENT : runtimeHelpers_1.RESOLVE_DIRECTIVE);
for (let i = 0; i < assets.length; i++) {
let id = assets[i];
// potential component implicit self-reference inferred from SFC filename
const maybeSelfReference = id.endsWith('__self');
if (maybeSelfReference) {
id = id.slice(0, -6);
}
let assetCode = '';
if (type === 'component') {
const source = matchEasyCom(id, false);
if (source) {
const easyComponentId = (0, compiler_core_1.toValidAssetId)(id, 'easycom');
const componentId = (0, compiler_core_1.toValidAssetId)(id, type);
assetCode = `const ${componentId} = ${helper(runtimeHelpers_1.RESOLVE_EASY_COMPONENT)}(${JSON.stringify(id)},${easyComponentId}${maybeSelfReference ? `, true` : ``})`;
const importCode = `import ${easyComponentId}${(0, utils_1.genImportComponentPublicInstance)(rootDir, id, source)} from '${source}';`;
if (!importEasyComponents.includes(importCode)) {
importEasyComponents.push(importCode);
}
}
}
if (!assetCode) {
assetCode = `const ${(0, compiler_core_1.toValidAssetId)(id, type)} = ${resolver}(${JSON.stringify(id)}${maybeSelfReference ? `, true` : ``})`;
}
push(assetCode);
if (i < assets.length - 1) {
newline();
}
}
}
function isText(n) {
return ((0, shared_1.isString)(n) ||
n.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ ||
n.type === 2 /* NodeTypes.TEXT */ ||
n.type === 5 /* NodeTypes.INTERPOLATION */ ||
n.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */);
}
function genNodeListAsArray(nodes, context) {
const multilines = nodes.length > 3 || nodes.some((n) => (0, shared_1.isArray)(n) || !isText(n));
context.push(`[`);
multilines && context.indent();
genNodeList(nodes, context, multilines);
multilines && context.deindent();
context.push(`]`);
}
function genNodeList(nodes, context, multilines = false, comma = true) {
const { push, newline } = context;
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i];
if ((0, shared_1.isString)(node)) {
push(node);
}
else if ((0, shared_1.isArray)(node)) {
genNodeListAsArray(node, context);
}
else {
genNode(node, context);
}
if (i < nodes.length - 1) {
if (multilines) {
comma && push(',');
newline();
}
else {
comma && push(', ');
}
}
}
}
function genNode(node, context) {
if ((0, shared_1.isString)(node)) {
context.push(node);
return;
}
if ((0, shared_1.isSymbol)(node)) {
context.push(context.helper(node));
return;
}
switch (node.type) {
case 1 /* NodeTypes.ELEMENT */:
case 9 /* NodeTypes.IF */:
case 11 /* NodeTypes.FOR */:
genNode(node.codegenNode, context);
break;
case 2 /* NodeTypes.TEXT */:
genText(node, context);
break;
case 4 /* NodeTypes.SIMPLE_EXPRESSION */:
genExpression(node, context);
break;
case 5 /* NodeTypes.INTERPOLATION */:
genInterpolation(node, context);
break;
case 12 /* NodeTypes.TEXT_CALL */:
genNode(node.codegenNode, context);
break;
case 8 /* NodeTypes.COMPOUND_EXPRESSION */:
genCompoundExpression(node, context);
break;
case 3 /* NodeTypes.COMMENT */:
genComment(node, context);
break;
case 13 /* NodeTypes.VNODE_CALL */:
genVNodeCall(node, context);
break;
case 14 /* NodeTypes.JS_CALL_EXPRESSION */:
genCallExpression(node, context);
break;
case 15 /* NodeTypes.JS_OBJECT_EXPRESSION */:
genObjectExpression(node, context);
break;
case 17 /* NodeTypes.JS_ARRAY_EXPRESSION */:
genArrayExpression(node, context);
break;
case 18 /* NodeTypes.JS_FUNCTION_EXPRESSION */:
genFunctionExpression(node, context);
break;
case 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */:
genConditionalExpression(node, context);
break;
case 20 /* NodeTypes.JS_CACHE_EXPRESSION */:
genCacheExpression(node, context);
break;
/* istanbul ignore next */
case 10 /* NodeTypes.IF_BRANCH */:
// noop
break;
default:
}
}
function genText(node, context) {
context.push(JSON.stringify(node.content), node);
}
function genExpression(node, context) {
const { content, isStatic } = node;
context.push(isStatic ? JSON.stringify(content) : content, node);
}
function genInterpolation(node, context) {
const { push, helper } = context;
push(`${helper(compiler_core_1.TO_DISPLAY_STRING)}(`);
genNode(node.content, context);
push(`)`);
}
function genCompoundExpression(node, context) {
for (let i = 0; i < node.children.length; i++) {
const child = node.children[i];
if ((0, shared_1.isString)(child)) {
context.push(child);
}
else {
genNode(child, context);
}
}
}
function genExpressionAsPropertyKey(node, context) {
const { push } = context;
if (node.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */) {
push(`[`);
genCompoundExpression(node, context);
push(`]`);
}
else if (node.isStatic) {
// only quote keys if necessary
const text = (0, compiler_core_1.isSimpleIdentifier)(node.content)
? node.content
: JSON.stringify(node.content);
push(text, node);
}
else {
push(`[${node.content}]`, node);
}
}
function genComment(node, context) {
const { push, helper } = context;
push(`${helper(compiler_core_1.CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node);
}
function parseTag(tag, { parseUTSComponent, targetLanguage, importUTSComponents }) {
if ((0, shared_1.isString)(tag)) {
// 原生UTS组件
const utsComponentOptions = parseUTSComponent(tag.slice(1, -1), targetLanguage);
if (utsComponentOptions) {
const importCode = `import '${utsComponentOptions.source}';`;
if (!importUTSComponents.includes(importCode)) {
importUTSComponents.push(importCode);
}
return (utsComponentOptions.namespace +
'.' +
utsComponentOptions.className +
'.name');
}
}
return tag;
}
function genVNodeCall(node, context) {
const { push, helper } = context;
const { tag, props, children, patchFlag, dynamicProps, directives,
// isBlock,
disableTracking, isComponent, } = node;
if (directives) {
push(helper(compiler_core_1.WITH_DIRECTIVES) + `(`);
}
const isBlock = false;
if (isBlock) {
push(`(${helper(compiler_core_1.OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
}
const callHelper = isBlock
? (0, compiler_core_1.getVNodeBlockHelper)(false, isComponent)
: (0, compiler_core_1.getVNodeHelper)(false, isComponent);
push(helper(callHelper) + `(`, node);
genNodeList(genNullableArgs([
parseTag(tag, context),
props,
children,
patchFlag,
dynamicProps,
]), context);
push(`)`);
if (isBlock) {
push(`)`);
}
if (directives) {
push(`, `);
genNode(directives, context);
push(`)`);
}
}
function genNullableArgs(args) {
let i = args.length;
while (i--) {
if (args[i] != null)
break;
}
return args.slice(0, i + 1).map((arg) => arg || `null`);
}
// JavaScript
function genCallExpression(node, context) {
const { push, helper } = context;
const callee = (0, shared_1.isString)(node.callee) ? node.callee : helper(node.callee);
push(callee + `(`, node);
if (callee === helper(runtimeHelpers_1.RENDER_LIST)) {
genRenderList(node);
}
genNodeList(node.arguments, context);
push(`)`);
}
function genRenderList(node) {
node.arguments.forEach((argument) => {
if (argument.type === 18 /* NodeTypes.JS_FUNCTION_EXPRESSION */) {
argument.returnType = 'VNode';
}
});
}
function genObjectExpression(node, context) {
const { push, indent, deindent, newline } = context;
const { properties } = node;
if (!properties.length) {
push(`utsMapOf()`, node);
return;
}
push(`utsMapOf(`);
const multilines = properties.length > 1 ||
properties.some((p) => p.value.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */);
push(multilines ? `{` : `{ `);
multilines && indent();
for (let i = 0; i < properties.length; i++) {
const { key, value } = properties[i];
// key
genExpressionAsPropertyKey(key, context);
push(`: `);
// value
genNode(value, context);
if (i < properties.length - 1) {
// will only reach this if it's multilines
push(`,`);
newline();
}
}
multilines && deindent();
push(multilines ? `}` : ` }`);
push(`)`);
}
function genArrayExpression(node, context) {
genNodeListAsArray(node.elements, context);
}
function genFunctionExpression(node, context) {
const { push, indent, deindent } = context;
const { params, returns, body, newline, isSlot } = node;
if (isSlot) {
// wrap slot functions with owner context
push(`${compiler_core_1.helperNameMap[compiler_core_1.WITH_CTX]}(`);
}
push(`(`, node);
if ((0, shared_1.isArray)(params)) {
genNodeList(params, context);
}
else if (params) {
if ((0, transformSlotPropsDestructuring_1.isDestructuringSlotProps)(isSlot, params) ||
params?.content === '{}') {
push(transformSlotPropsDestructuring_1.SLOT_PROPS_NAME);
}
else {
genNode(params, context);
}
}
if (node.returnType) {
push(`): ${node.returnType} => `);
}
else {
if (isSlot) {
if (params) {
push(`: Map<string, any | null>): any[] => `);
if ((0, transformSlotPropsDestructuring_1.isDestructuringSlotProps)(isSlot, params)) {
push('{');
(0, transformSlotPropsDestructuring_1.createDestructuringSlotProps)(params, context);
context.newline();
push('return ');
}
}
else {
push(`): any[] => `);
}
}
else {
push(`) => `);
}
}
if (newline || body) {
push(`{`);
indent();
}
if (returns) {
if (newline) {
push(`return `);
}
if ((0, shared_1.isArray)(returns)) {
genNodeListAsArray(returns, context);
}
else {
genNode(returns, context);
}
}
else if (body) {
genNode(body, context);
}
if (newline || body) {
deindent();
push(`}`);
}
if (isSlot) {
if ((0, transformSlotPropsDestructuring_1.isDestructuringSlotProps)(isSlot, params)) {
push('}');
}
push(`)`);
}
}
const booleanBinExprOperators = ['==', '===', '!=', '!==', '<', '>', '<=', '>='];
function shouldWrapperConditionalTest(test, context) {
const isSimpleExpr = (0, uni_cli_shared_1.isSimpleExpressionNode)(test);
if (isSimpleExpr) {
const { content } = test;
if (content === 'true' || content === 'false') {
return false;
}
}
if (isSimpleExpr || (0, uni_cli_shared_1.isCompoundExpressionNode)(test)) {
const code = (0, transformExpression_1.stringifyExpression)(test);
const ast = (0, parser_1.parseExpression)(code, {
plugins: context.expressionPlugins,
});
if ((0, types_1.isBinaryExpression)(ast)) {
// 先简易解析
if (booleanBinExprOperators.includes(ast.operator)) {
return false;
}
}
}
return true;
}
function genConditionalExpression(node, context) {
const { test, consequent, alternate, newline: needNewline } = node;
const { push, indent, deindent, newline } = context;
const wrapper = shouldWrapperConditionalTest(test, context);
wrapper && push(`${context.helper(runtimeHelpers_1.IS_TRUE)}(`);
if (test.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
genExpression(test, context);
}
else {
genNode(test, context);
}
wrapper && push(`)`);
needNewline && indent();
context.indentLevel++;
needNewline || push(` `);
push(`? `);
genNode(consequent, context);
context.indentLevel--;
needNewline && newline();
needNewline || push(` `);
push(`: `);
const isNested = alternate.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */;
if (!isNested) {
context.indentLevel++;
}
genNode(alternate, context);
if (!isNested) {
context.indentLevel--;
}
needNewline && deindent(true /* without newline */);
}
function genCacheExpression(node, context) {
const { push, helper, indent, deindent, newline } = context;
push(`_cache[${node.index}] || (`);
if (node.isVNode) {
indent();
push(`${helper(compiler_core_1.SET_BLOCK_TRACKING)}(-1),`);
newline();
}
push(`_cache[${node.index}] = `);
genNode(node.value, context);
if (node.isVNode) {
push(`,`);
newline();
push(`${helper(compiler_core_1.SET_BLOCK_TRACKING)}(1),`);
newline();
push(`_cache[${node.index}]`);
deindent();
}
push(`)`);
}

View File

@@ -0,0 +1,70 @@
import { SourceLocation } from '@vue/compiler-core';
export interface CompilerError extends SyntaxError {
code: number | string;
loc?: SourceLocation;
}
export interface CoreCompilerError extends CompilerError {
code: ErrorCodes;
}
export declare function defaultOnError(error: CompilerError): void;
export declare function defaultOnWarn(msg: CompilerError): void;
type InferCompilerError<T> = T extends ErrorCodes ? CoreCompilerError : CompilerError;
export declare function createCompilerError<T extends number>(code: T, loc?: SourceLocation, messages?: {
[code: number]: string;
}, additionalMessage?: string): InferCompilerError<T>;
export declare const enum ErrorCodes {
ABRUPT_CLOSING_OF_EMPTY_COMMENT = 0,
CDATA_IN_HTML_CONTENT = 1,
DUPLICATE_ATTRIBUTE = 2,
END_TAG_WITH_ATTRIBUTES = 3,
END_TAG_WITH_TRAILING_SOLIDUS = 4,
EOF_BEFORE_TAG_NAME = 5,
EOF_IN_CDATA = 6,
EOF_IN_COMMENT = 7,
EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT = 8,
EOF_IN_TAG = 9,
INCORRECTLY_CLOSED_COMMENT = 10,
INCORRECTLY_OPENED_COMMENT = 11,
INVALID_FIRST_CHARACTER_OF_TAG_NAME = 12,
MISSING_ATTRIBUTE_VALUE = 13,
MISSING_END_TAG_NAME = 14,
MISSING_WHITESPACE_BETWEEN_ATTRIBUTES = 15,
NESTED_COMMENT = 16,
UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME = 17,
UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE = 18,
UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME = 19,
UNEXPECTED_NULL_CHARACTER = 20,
UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME = 21,
UNEXPECTED_SOLIDUS_IN_TAG = 22,
X_INVALID_END_TAG = 23,
X_MISSING_END_TAG = 24,
X_MISSING_INTERPOLATION_END = 25,
X_MISSING_DIRECTIVE_NAME = 26,
X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END = 27,
X_V_IF_NO_EXPRESSION = 28,
X_V_IF_SAME_KEY = 29,
X_V_ELSE_NO_ADJACENT_IF = 30,
X_V_FOR_NO_EXPRESSION = 31,
X_V_FOR_MALFORMED_EXPRESSION = 32,
X_V_FOR_TEMPLATE_KEY_PLACEMENT = 33,
X_V_BIND_NO_EXPRESSION = 34,
X_V_ON_NO_EXPRESSION = 35,
X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET = 36,
X_V_SLOT_MIXED_SLOT_USAGE = 37,
X_V_SLOT_DUPLICATE_SLOT_NAMES = 38,
X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN = 39,
X_V_SLOT_MISPLACED = 40,
X_V_MODEL_NO_EXPRESSION = 41,
X_V_MODEL_MALFORMED_EXPRESSION = 42,
X_V_MODEL_ON_SCOPE_VARIABLE = 43,
X_V_MODEL_ON_PROPS = 44,
X_INVALID_EXPRESSION = 45,
X_KEEP_ALIVE_INVALID_CHILDREN = 46,
X_PREFIX_ID_NOT_SUPPORTED = 47,
X_MODULE_MODE_NOT_SUPPORTED = 48,
X_CACHE_HANDLER_NOT_SUPPORTED = 49,
X_SCOPE_ID_NOT_SUPPORTED = 50,
__EXTEND_POINT__ = 51
}
export declare const errorMessages: Record<ErrorCodes, string>;
export {};

View File

@@ -0,0 +1,82 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.errorMessages = exports.createCompilerError = exports.defaultOnWarn = exports.defaultOnError = void 0;
function defaultOnError(error) {
throw error;
}
exports.defaultOnError = defaultOnError;
function defaultOnWarn(msg) {
console.warn(`[Vue warn] ${msg.message}`);
}
exports.defaultOnWarn = defaultOnWarn;
function createCompilerError(code, loc, messages, additionalMessage) {
const msg = (messages || exports.errorMessages)[code] + (additionalMessage || ``);
const error = new SyntaxError(String(msg));
error.code = code;
error.loc = loc;
return error;
}
exports.createCompilerError = createCompilerError;
exports.errorMessages = {
// parse errors
[0 /* ErrorCodes.ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',
[1 /* ErrorCodes.CDATA_IN_HTML_CONTENT */]: 'CDATA section is allowed only in XML context.',
[2 /* ErrorCodes.DUPLICATE_ATTRIBUTE */]: 'Duplicate attribute.',
[3 /* ErrorCodes.END_TAG_WITH_ATTRIBUTES */]: 'End tag cannot have attributes.',
[4 /* ErrorCodes.END_TAG_WITH_TRAILING_SOLIDUS */]: "Illegal '/' in tags.",
[5 /* ErrorCodes.EOF_BEFORE_TAG_NAME */]: 'Unexpected EOF in tag.',
[6 /* ErrorCodes.EOF_IN_CDATA */]: 'Unexpected EOF in CDATA section.',
[7 /* ErrorCodes.EOF_IN_COMMENT */]: 'Unexpected EOF in comment.',
[8 /* ErrorCodes.EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */]: 'Unexpected EOF in script.',
[9 /* ErrorCodes.EOF_IN_TAG */]: 'Unexpected EOF in tag.',
[10 /* ErrorCodes.INCORRECTLY_CLOSED_COMMENT */]: 'Incorrectly closed comment.',
[11 /* ErrorCodes.INCORRECTLY_OPENED_COMMENT */]: 'Incorrectly opened comment.',
[12 /* ErrorCodes.INVALID_FIRST_CHARACTER_OF_TAG_NAME */]: "Illegal tag name. Use '&lt;' to print '<'.",
[13 /* ErrorCodes.MISSING_ATTRIBUTE_VALUE */]: 'Attribute value was expected.',
[14 /* ErrorCodes.MISSING_END_TAG_NAME */]: 'End tag name was expected.',
[15 /* ErrorCodes.MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */]: 'Whitespace was expected.',
[16 /* ErrorCodes.NESTED_COMMENT */]: "Unexpected '<!--' in comment.",
[17 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).',
[18 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).',
[19 /* ErrorCodes.UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */]: "Attribute name cannot start with '='.",
[21 /* ErrorCodes.UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */]: "'<?' is allowed only in XML context.",
[20 /* ErrorCodes.UNEXPECTED_NULL_CHARACTER */]: `Unexpected null character.`,
[22 /* ErrorCodes.UNEXPECTED_SOLIDUS_IN_TAG */]: "Illegal '/' in tags.",
// Vue-specific parse errors
[23 /* ErrorCodes.X_INVALID_END_TAG */]: 'Invalid end tag.',
[24 /* ErrorCodes.X_MISSING_END_TAG */]: 'Element is missing end tag.',
[25 /* ErrorCodes.X_MISSING_INTERPOLATION_END */]: 'Interpolation end sign was not found.',
[27 /* ErrorCodes.X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
'Note that dynamic directive argument cannot contain spaces.',
[26 /* ErrorCodes.X_MISSING_DIRECTIVE_NAME */]: 'Legal directive name was expected.',
// transform errors
[28 /* ErrorCodes.X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
[29 /* ErrorCodes.X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
[30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if or v-else-if.`,
[31 /* ErrorCodes.X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
[32 /* ErrorCodes.X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
[33 /* ErrorCodes.X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
[34 /* ErrorCodes.X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
[35 /* ErrorCodes.X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
[36 /* ErrorCodes.X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
[37 /* ErrorCodes.X_V_SLOT_MIXED_SLOT_USAGE */]: `Mixed v-slot usage on both the component and nested <template>. ` +
`When there are multiple named slots, all slots should use <template> ` +
`syntax to avoid scope ambiguity.`,
[38 /* ErrorCodes.X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
[39 /* ErrorCodes.X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
`default slot. These children will be ignored.`,
[40 /* ErrorCodes.X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
[41 /* ErrorCodes.X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
[42 /* ErrorCodes.X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
[43 /* ErrorCodes.X_V_MODEL_ON_SCOPE_VARIABLE */]: `v-model cannot be used on v-for or v-slot scope variables because they are not writable.`,
[44 /* ErrorCodes.X_V_MODEL_ON_PROPS */]: `v-model cannot be used on a prop, because local prop bindings are not writable.\nUse a v-bind binding combined with a v-on listener that emits update:x event instead.`,
[45 /* ErrorCodes.X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
[46 /* ErrorCodes.X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
// generic errors
[47 /* ErrorCodes.X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
[48 /* ErrorCodes.X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
[49 /* ErrorCodes.X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
[50 /* ErrorCodes.X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`,
// just to fulfill types
[51 /* ErrorCodes.__EXTEND_POINT__ */]: ``,
};

View File

@@ -0,0 +1,9 @@
import './runtimeHelpers';
import { CodegenResult, CompilerOptions } from './options';
import { DirectiveTransform, NodeTransform } from './transform';
export type TransformPreset = [
NodeTransform[],
Record<string, DirectiveTransform>
];
export declare function getBaseTransformPreset(prefixIdentifiers?: boolean): TransformPreset;
export declare function compile(template: string, options: CompilerOptions): CodegenResult;

View File

@@ -0,0 +1,73 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.compile = exports.getBaseTransformPreset = void 0;
const shared_1 = require("@vue/shared");
const compiler_core_1 = require("@vue/compiler-core");
const uni_shared_1 = require("@dcloudio/uni-shared");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
require("./runtimeHelpers");
const codegen_1 = require("./codegen");
const transform_1 = require("./transform");
const vIf_1 = require("./transforms/vIf");
const vFor_1 = require("./transforms/vFor");
const vModel_1 = require("./transforms/vModel");
const vShow_1 = require("./transforms/vShow");
const vText_1 = require("./transforms/vText");
const transformInterpolation_1 = require("./transforms/transformInterpolation");
const transformText_1 = require("./transforms/transformText");
const vOnWithModifier_1 = require("./transforms/vOnWithModifier");
const vBind_1 = require("./transforms/vBind");
const transformSlotOutlet_1 = require("./transforms/transformSlotOutlet");
const transformObjectExpression_1 = require("./transforms/transformObjectExpression");
const transformExpression_1 = require("./transforms/transformExpression");
const transformElements_1 = require("./transforms/transformElements");
const transformStyle_1 = require("./transforms/transformStyle");
function getBaseTransformPreset(prefixIdentifiers) {
return [
[
vIf_1.transformIf,
vFor_1.transformFor,
// order is important
compiler_core_1.trackVForSlotScopes,
transformExpression_1.transformExpression,
transformSlotOutlet_1.transformSlotOutlet,
compiler_core_1.transformElement,
compiler_core_1.trackSlotScopes,
transformText_1.transformText,
uni_cli_shared_1.transformTapToClick,
transformInterpolation_1.transformInterpolation,
transformObjectExpression_1.transformObjectExpression,
transformElements_1.transformElements,
transformStyle_1.transformStyle,
],
{
on: vOnWithModifier_1.transformOn,
bind: vBind_1.transformBind,
model: vModel_1.transformModel,
show: vShow_1.transformShow,
text: vText_1.transformVText,
},
];
}
exports.getBaseTransformPreset = getBaseTransformPreset;
function compile(template, options) {
const ast = (0, compiler_core_1.baseParse)(template, {
comments: false,
isNativeTag(tag) {
return ((0, uni_shared_1.isAppUVueNativeTag)(tag) ||
!!options.parseUTSComponent?.(tag, options.targetLanguage));
},
});
const [nodeTransforms, directiveTransforms] = getBaseTransformPreset(options.prefixIdentifiers);
(0, transform_1.transform)(ast, (0, shared_1.extend)({}, options, {
prefixIdentifiers: options.prefixIdentifiers,
nodeTransforms: [
...nodeTransforms,
...(options.nodeTransforms || []), // user transforms
],
directiveTransforms: (0, shared_1.extend)({}, directiveTransforms, options.directiveTransforms || {} // user transforms
),
}));
return (0, codegen_1.generate)(ast, options);
}
exports.compile = compile;

View File

@@ -0,0 +1,99 @@
import { BindingMetadata, CompilerError } from '@vue/compiler-core';
import type { RawSourceMap } from 'source-map-js';
import { DirectiveTransform, NodeTransform } from './transform';
interface SharedTransformCodegenOptions {
rootDir: string;
targetLanguage: 'kotlin' | 'swift';
/**
* Transform expressions like {{ foo }} to `_ctx.foo`.
* @default false
*/
prefixIdentifiers?: boolean;
/**
* Optional binding metadata analyzed from script - used to optimize
* binding access when `prefixIdentifiers` is enabled.
*/
bindingMetadata?: BindingMetadata;
/**
* Filename for source map generation.
* Also used for self-recursive reference in templates
* @default ''
*/
filename?: string;
/**
* 编译的模板类名
*/
className?: string;
}
export interface CodegenOptions extends SharedTransformCodegenOptions {
/**
* function
* @default 'default'
*/
mode?: 'default' | 'function';
/**
* Generate source map?
* @default false
*/
sourceMap?: boolean;
/**
* 匹配 easycom 组件
* @param tag
*/
matchEasyCom?: (tag: string, uts: boolean) => string | false | undefined | void;
/**
* 解析 uts component 组件
* @param name
* @param type
*/
parseUTSComponent?: (name: string, type: 'kotlin' | 'swift') => {
className: string;
namespace: string;
source: string;
} | undefined | void;
}
export interface ErrorHandlingOptions {
onWarn?: (warning: CompilerError) => void;
onError?: (error: CompilerError) => void;
}
export interface TransformOptions extends SharedTransformCodegenOptions, ErrorHandlingOptions {
rootDir: string;
/**
* An array of node transforms to be applied to every AST node.
*/
nodeTransforms?: NodeTransform[];
/**
* An object of { name: transform } to be applied to every directive attribute
* node found on element nodes.
*/
directiveTransforms?: Record<string, DirectiveTransform | undefined>;
/**
* If the pairing runtime provides additional built-in elements, use this to
* mark them as built-in so the compiler will generate component vnodes
* for them.
*/
isBuiltInComponent?: (tag: string) => symbol | void;
/**
* Used by some transforms that expects only native elements
*/
isCustomElement?: (tag: string) => boolean | void;
/**
* SFC scoped styles ID
*/
scopeId?: string | null;
/**
* Indicates this SFC template has used :slotted in its styles
* Defaults to `true` for backwards compatibility - SFC tooling should set it
* to `false` if no `:slotted` usage is detected in `<style>`
*/
slotted?: boolean;
}
export type CompilerOptions = TransformOptions & CodegenOptions;
export interface CodegenResult {
code: string;
importEasyComponents: string[];
importUTSComponents: string[];
elements: string[];
map?: RawSourceMap;
}
export {};

View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

View File

@@ -0,0 +1,11 @@
export declare const IS_TRUE: unique symbol;
export declare const V_SHOW: unique symbol;
export declare const RENDER_LIST: unique symbol;
export declare const FRAGMENT: unique symbol;
export declare const OPEN_BLOCK: unique symbol;
export declare const RESOLVE_COMPONENT: unique symbol;
export declare const RESOLVE_DIRECTIVE: unique symbol;
export declare const RESOLVE_EASY_COMPONENT: unique symbol;
export declare const RENDER_SLOT: unique symbol;
export declare const TO_HANDLERS: unique symbol;
export declare const V_ON_WITH_MODIFIERS: unique symbol;

View File

@@ -0,0 +1,27 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.V_ON_WITH_MODIFIERS = exports.TO_HANDLERS = exports.RENDER_SLOT = exports.RESOLVE_EASY_COMPONENT = exports.RESOLVE_DIRECTIVE = exports.RESOLVE_COMPONENT = exports.OPEN_BLOCK = exports.FRAGMENT = exports.RENDER_LIST = exports.V_SHOW = exports.IS_TRUE = void 0;
const compiler_core_1 = require("@vue/compiler-core");
exports.IS_TRUE = Symbol(`isTrue`);
exports.V_SHOW = Symbol(`vShow`);
exports.RENDER_LIST = Symbol(`renderList`);
exports.FRAGMENT = Symbol(`Fragment`);
exports.OPEN_BLOCK = Symbol(`openBlock`);
exports.RESOLVE_COMPONENT = Symbol(`resolveComponent`);
exports.RESOLVE_DIRECTIVE = Symbol(`resolveDirective`);
exports.RESOLVE_EASY_COMPONENT = Symbol(`resolveEasyComponent`);
exports.RENDER_SLOT = Symbol(`renderSlot`);
exports.TO_HANDLERS = Symbol(`toHandlers`);
exports.V_ON_WITH_MODIFIERS = Symbol(`vOnModifiersGuard`);
(0, compiler_core_1.registerRuntimeHelpers)({
[exports.IS_TRUE]: 'isTrue',
[exports.V_SHOW]: 'vShow',
[exports.RENDER_LIST]: 'RenderHelpers.renderList',
[exports.FRAGMENT]: 'Fragment',
[exports.RESOLVE_COMPONENT]: 'resolveComponent',
[exports.RESOLVE_EASY_COMPONENT]: 'resolveEasyComponent',
[exports.RESOLVE_DIRECTIVE]: 'resolveDirective',
[exports.RENDER_SLOT]: `renderSlot`,
[exports.TO_HANDLERS]: `toHandlers`,
[exports.V_ON_WITH_MODIFIERS]: `withModifiers`,
});

View File

@@ -0,0 +1,56 @@
import { CacheExpression, ComponentNode, ConstantTypes, DirectiveNode, ElementNode, ExpressionNode, JSChildNode, ParentNode, PlainElementNode, Property, RootNode, TemplateChildNode, TemplateLiteral, TemplateNode } from '@vue/compiler-core';
import { TransformOptions } from './options';
import { ParserPlugin } from '@babel/parser';
export type NodeTransform = (node: RootNode | TemplateChildNode, context: TransformContext) => void | (() => void) | (() => void)[];
export type DirectiveTransform = (dir: DirectiveNode, node: ElementNode, context: TransformContext, augmentor?: (ret: DirectiveTransformResult) => DirectiveTransformResult) => DirectiveTransformResult;
export interface DirectiveTransformResult {
props: Property[];
needRuntime?: boolean | symbol;
ssrTagParts?: TemplateLiteral['elements'];
}
export type StructuralDirectiveTransform = (node: ElementNode, dir: DirectiveNode, context: TransformContext) => void | (() => void);
export interface ImportItem {
exp: string | ExpressionNode;
path: string;
}
export interface TransformContext extends Required<Omit<TransformOptions, 'filename' | 'className'>> {
selfName: string | null;
root: RootNode;
helpers: Map<symbol, number>;
components: Set<string>;
directives: Set<string>;
imports: ImportItem[];
temps: number;
cached: number;
identifiers: {
[name: string]: number | undefined;
};
scopes: {
vFor: number;
vSlot: number;
vPre: number;
vOnce: number;
};
parent: ParentNode | null;
childIndex: number;
currentNode: RootNode | TemplateChildNode | null;
inVOnce: boolean;
expressionPlugins: ParserPlugin[];
helper<T extends symbol>(name: T): T;
removeHelper<T extends symbol>(name: T): void;
helperString(name: symbol): string;
replaceNode(node: TemplateChildNode): void;
removeNode(node?: TemplateChildNode): void;
onNodeRemoved(): void;
addIdentifiers(exp: ExpressionNode | string): void;
removeIdentifiers(exp: ExpressionNode | string): void;
cache<T extends JSChildNode>(exp: T, isVNode?: boolean): CacheExpression | T;
constantCache: Map<TemplateChildNode, ConstantTypes>;
elements: Set<string>;
}
export declare function createTransformContext(root: RootNode, { rootDir, targetLanguage, filename, prefixIdentifiers, nodeTransforms, directiveTransforms, scopeId, slotted, isBuiltInComponent, isCustomElement, onError, onWarn, }: TransformOptions): TransformContext;
export declare function transform(root: RootNode, options: TransformOptions): void;
export declare function isSingleElementRoot(root: RootNode, child: TemplateChildNode): child is PlainElementNode | ComponentNode | TemplateNode;
export declare function traverseChildren(parent: ParentNode, context: TransformContext): void;
export declare function traverseNode(node: RootNode | TemplateChildNode, context: TransformContext): void;
export declare function createStructuralDirectiveTransform(name: string | RegExp, fn: StructuralDirectiveTransform): NodeTransform;

View File

@@ -0,0 +1,299 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createStructuralDirectiveTransform = exports.traverseNode = exports.traverseChildren = exports.isSingleElementRoot = exports.transform = exports.createTransformContext = void 0;
const compiler_core_1 = require("@vue/compiler-core");
const shared_1 = require("@vue/shared");
const errors_1 = require("./errors");
const runtimeHelpers_1 = require("./runtimeHelpers");
function createTransformContext(root, { rootDir, targetLanguage, filename = '', prefixIdentifiers = false, nodeTransforms = [], directiveTransforms = {}, scopeId = null, slotted = true, isBuiltInComponent = shared_1.NOOP, isCustomElement = shared_1.NOOP, onError = errors_1.defaultOnError, onWarn = errors_1.defaultOnWarn, }) {
const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/);
const context = {
// options
rootDir,
targetLanguage,
selfName: nameMatch && (0, shared_1.capitalize)((0, shared_1.camelize)(nameMatch[1])),
prefixIdentifiers,
bindingMetadata: {},
nodeTransforms,
directiveTransforms,
elements: new Set(),
isBuiltInComponent,
isCustomElement,
scopeId,
slotted,
onError,
onWarn,
// state
root,
helpers: new Map(),
components: new Set(),
directives: new Set(),
imports: [],
constantCache: new Map(),
temps: 0,
cached: 0,
identifiers: Object.create(null),
scopes: {
vFor: 0,
vSlot: 0,
vPre: 0,
vOnce: 0,
},
parent: null,
currentNode: root,
childIndex: 0,
inVOnce: false,
expressionPlugins: ['typescript'],
// methods
helper(name) {
const count = context.helpers.get(name) || 0;
context.helpers.set(name, count + 1);
return name;
},
removeHelper(name) {
const count = context.helpers.get(name);
if (count) {
const currentCount = count - 1;
if (!currentCount) {
context.helpers.delete(name);
}
else {
context.helpers.set(name, currentCount);
}
}
},
helperString(name) {
// return `_${helperNameMap[context.helper(name)]}`
return `${compiler_core_1.helperNameMap[context.helper(name)]}`;
},
replaceNode(node) {
if (!context.currentNode) {
throw new Error(`Node being replaced is already removed.`);
}
if (!context.parent) {
throw new Error(`Cannot replace root node.`);
}
context.parent.children[context.childIndex] = context.currentNode = node;
},
removeNode(node) {
if (!context.parent) {
throw new Error(`Cannot remove root node.`);
}
const list = context.parent.children;
const removalIndex = node
? list.indexOf(node)
: context.currentNode
? context.childIndex
: -1;
/* istanbul ignore if */
if (removalIndex < 0) {
throw new Error(`node being removed is not a child of current parent`);
}
if (!node || node === context.currentNode) {
// current node removed
context.currentNode = null;
context.onNodeRemoved();
}
else {
// sibling node removed
if (context.childIndex > removalIndex) {
context.childIndex--;
context.onNodeRemoved();
}
}
context.parent.children.splice(removalIndex, 1);
},
onNodeRemoved: () => { },
addIdentifiers(exp) {
// identifier tracking only happens in non-browser builds.
if ((0, shared_1.isString)(exp)) {
addId(exp);
}
else if (exp.identifiers) {
exp.identifiers.forEach(addId);
}
else if (exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
addId(exp.content);
}
},
removeIdentifiers(exp) {
if ((0, shared_1.isString)(exp)) {
removeId(exp);
}
else if (exp.identifiers) {
exp.identifiers.forEach(removeId);
}
else if (exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
removeId(exp.content);
}
},
cache(exp, isVNode = false) {
return (0, compiler_core_1.createCacheExpression)(context.cached++, exp, isVNode);
},
};
function addId(id) {
const { identifiers } = context;
if (identifiers[id] === undefined) {
identifiers[id] = 0;
}
identifiers[id]++;
}
function removeId(id) {
context.identifiers[id]--;
}
return context;
}
exports.createTransformContext = createTransformContext;
function transform(root, options) {
const context = createTransformContext(root, options);
traverseNode(root, context);
createRootCodegen(root, context);
root.components = [...context.components];
// @ts-ignore
root.elements = Array.from(context.elements);
}
exports.transform = transform;
function isSingleElementRoot(root, child) {
const { children } = root;
return (children.length === 1 &&
child.type === 1 /* NodeTypes.ELEMENT */ &&
!(0, compiler_core_1.isSlotOutlet)(child));
}
exports.isSingleElementRoot = isSingleElementRoot;
function createRootCodegen(root, context) {
const { helper } = context;
const { children } = root;
if (children.length === 1) {
const child = children[0];
// if the single child is an element, turn it into a block.
if (isSingleElementRoot(root, child) && child.codegenNode) {
// single element root is never hoisted so codegenNode will never be
// SimpleExpressionNode
const codegenNode = child.codegenNode;
if (codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
(0, compiler_core_1.makeBlock)(codegenNode, context);
}
root.codegenNode = codegenNode;
}
else {
// - single <slot/>, IfNode, ForNode: already blocks.
// - single text node: always patched.
// root codegen falls through via genNode()
root.codegenNode = child;
}
}
else if (children.length > 1) {
// root has multiple nodes - return a fragment block.
let patchFlag = 64 /* PatchFlags.STABLE_FRAGMENT */;
let patchFlagText = shared_1.PatchFlagNames[64 /* PatchFlags.STABLE_FRAGMENT */];
// check if the fragment actually contains a single valid child with
// the rest being comments
if (children.filter((c) => c.type !== 3 /* NodeTypes.COMMENT */).length === 1) {
patchFlag |= 2048 /* PatchFlags.DEV_ROOT_FRAGMENT */;
patchFlagText += `, ${shared_1.PatchFlagNames[2048 /* PatchFlags.DEV_ROOT_FRAGMENT */]}`;
}
root.codegenNode = (0, compiler_core_1.createVNodeCall)(
// @ts-ignore
context, helper(runtimeHelpers_1.FRAGMENT), undefined, root.children, patchFlag + ` /* ${patchFlagText} */`, undefined, undefined, true, undefined, false /* isComponent */);
}
else {
// no children = noop. codegen will return null.
}
}
function traverseChildren(parent, context) {
let i = 0;
const nodeRemoved = () => {
i--;
};
for (; i < parent.children.length; i++) {
const child = parent.children[i];
if ((0, shared_1.isString)(child))
continue;
context.parent = parent;
context.childIndex = i;
context.onNodeRemoved = nodeRemoved;
traverseNode(child, context);
}
}
exports.traverseChildren = traverseChildren;
function traverseNode(node, context) {
context.currentNode = node;
// apply transform plugins
const { nodeTransforms } = context;
const exitFns = [];
for (let i = 0; i < nodeTransforms.length; i++) {
const onExit = nodeTransforms[i](node, context);
if (onExit) {
if ((0, shared_1.isArray)(onExit)) {
exitFns.push(...onExit);
}
else {
exitFns.push(onExit);
}
}
if (!context.currentNode) {
// node was removed
return;
}
else {
// node may have been replaced
node = context.currentNode;
}
}
switch (node.type) {
case 3 /* NodeTypes.COMMENT */:
break;
case 5 /* NodeTypes.INTERPOLATION */:
break;
// for container types, further traverse downwards
case 9 /* NodeTypes.IF */:
for (let i = 0; i < node.branches.length; i++) {
traverseNode(node.branches[i], context);
}
break;
case 10 /* NodeTypes.IF_BRANCH */:
case 11 /* NodeTypes.FOR */:
case 1 /* NodeTypes.ELEMENT */:
case 0 /* NodeTypes.ROOT */:
traverseChildren(node, context);
break;
}
// exit transforms
context.currentNode = node;
let i = exitFns.length;
while (i--) {
exitFns[i]();
}
}
exports.traverseNode = traverseNode;
function createStructuralDirectiveTransform(name, fn) {
const matches = (0, shared_1.isString)(name)
? (n) => n === name
: (n) => name.test(n);
return (node, context) => {
if (node.type === 1 /* NodeTypes.ELEMENT */) {
const { props } = node;
// structural directive transforms are not concerned with slots
// as they are handled separately in vSlot.ts
if (node.tagType === 3 /* ElementTypes.TEMPLATE */ && props.some(compiler_core_1.isVSlot)) {
return;
}
const exitFns = [];
for (let i = 0; i < props.length; i++) {
const prop = props[i];
if (prop.type === 7 /* NodeTypes.DIRECTIVE */ && matches(prop.name)) {
// structural directives are removed to avoid infinite recursion
// also we remove them *before* applying so that it can further
// traverse itself in case it moves the node around
props.splice(i, 1);
i--;
const onExit = fn(node, prop, context);
if (onExit)
exitFns.push(onExit);
}
}
return exitFns;
}
};
}
exports.createStructuralDirectiveTransform = createStructuralDirectiveTransform;

View File

@@ -0,0 +1,3 @@
import { RootNode, TemplateChildNode } from '@vue/compiler-core';
import { TransformContext } from '../transform';
export declare function transformElements(node: RootNode | TemplateChildNode, context: TransformContext): void;

View File

@@ -0,0 +1,10 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformElements = void 0;
function transformElements(node, context) {
if (node.type === 1 /* NodeTypes.ELEMENT */ &&
node.tagType === 0 /* ElementTypes.ELEMENT */) {
context.elements.add(node.tag);
}
}
exports.transformElements = transformElements;

View File

@@ -0,0 +1,5 @@
import { NodeTransform, TransformContext } from '../transform';
import { ExpressionNode, SimpleExpressionNode } from '@vue/compiler-core';
export declare const transformExpression: NodeTransform;
export declare function processExpression(node: SimpleExpressionNode, context: TransformContext, asParams?: boolean, asRawStatements?: boolean, localVars?: Record<string, number>): ExpressionNode;
export declare function stringifyExpression(exp: ExpressionNode | string): string;

View File

@@ -0,0 +1,213 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.stringifyExpression = exports.processExpression = exports.transformExpression = void 0;
const shared_1 = require("@vue/shared");
const parser_1 = require("@babel/parser");
const compiler_core_1 = require("@vue/compiler-core");
const errors_1 = require("../errors");
const GLOBALS_WHITE_LISTED = `Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI` +
`,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array` +
`,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt` +
`,console`;
const isGloballyWhitelisted = /*#__PURE__*/ (0, shared_1.makeMap)(GLOBALS_WHITE_LISTED);
const isLiteralWhitelisted = /*#__PURE__*/ (0, shared_1.makeMap)('true,false,null,this');
const transformExpression = (node, context) => {
if (node.type === 5 /* NodeTypes.INTERPOLATION */) {
node.content = processExpression(node.content, context);
}
else if (node.type === 1 /* NodeTypes.ELEMENT */) {
// handle directives on element
for (let i = 0; i < node.props.length; i++) {
const dir = node.props[i];
// do not process for v-on & v-for since they are special handled
if (dir.type === 7 /* NodeTypes.DIRECTIVE */ && dir.name !== 'for') {
const exp = dir.exp;
const arg = dir.arg;
// do not process exp if this is v-on:arg - we need special handling
// for wrapping inline statements.
if (exp &&
exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
!(dir.name === 'on' && arg)) {
dir.exp = processExpression(exp, context,
// slot args must be processed as function params
dir.name === 'slot');
}
if (arg && arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && !arg.isStatic) {
dir.arg = processExpression(arg, context);
}
}
}
}
};
exports.transformExpression = transformExpression;
// Important: since this function uses Node.js only dependencies, it should
// always be used with a leading !__BROWSER__ check so that it can be
// tree-shaken from the browser build.
function processExpression(node, context,
// some expressions like v-slot props & v-for aliases should be parsed as
// function params
asParams = false,
// v-on handler values may contain multiple statements
asRawStatements = false, localVars = Object.create(context.identifiers)) {
if (!context.prefixIdentifiers || !node.content.trim()) {
return node;
}
const { bindingMetadata } = context;
const rewriteIdentifier = (raw, parent, id) => {
const type = (0, shared_1.hasOwn)(bindingMetadata, raw) && bindingMetadata[raw];
if (type && type.startsWith('setup')) {
// setup bindings in non-inline mode
return `$setup.${raw}`;
}
else if (type === "props-aliased" /* BindingTypes.PROPS_ALIASED */) {
return `$props['${bindingMetadata.__propsAliases[raw]}']`;
}
else if (type) {
return `$${type}.${raw}`;
}
// fallback to ctx
return `_ctx.${raw}`;
};
// fast path if expression is a simple identifier.
const rawExp = node.content;
// bail constant on parens (function invocation) and dot (member access)
const bailConstant = rawExp.indexOf(`(`) > -1 || rawExp.indexOf('.') > 0;
if ((0, compiler_core_1.isSimpleIdentifier)(rawExp)) {
const isScopeVarReference = context.identifiers[rawExp];
const isAllowedGlobal = isGloballyWhitelisted(rawExp);
const isLiteral = isLiteralWhitelisted(rawExp);
if (!asParams && !isScopeVarReference && !isAllowedGlobal && !isLiteral) {
// const bindings exposed from setup can be skipped for patching but
// cannot be hoisted to module scope
if (bindingMetadata[node.content] === "setup-const" /* BindingTypes.SETUP_CONST */) {
node.constType = 1 /* ConstantTypes.CAN_SKIP_PATCH */;
}
node.content = rewriteIdentifier(rawExp);
}
else if (!isScopeVarReference) {
if (isLiteral) {
node.constType = 3 /* ConstantTypes.CAN_STRINGIFY */;
}
else {
node.constType = 2 /* ConstantTypes.CAN_HOIST */;
}
}
return node;
}
let ast;
// exp needs to be parsed differently:
// 1. Multiple inline statements (v-on, with presence of `;`): parse as raw
// exp, but make sure to pad with spaces for consistent ranges
// 2. Expressions: wrap with parens (for e.g. object expressions)
// 3. Function arguments (v-for, v-slot): place in a function argument position
const source = asRawStatements
? ` ${rawExp} `
: `(${rawExp})${asParams ? `=>{}` : ``}`;
try {
ast = (0, parser_1.parse)(source, {
plugins: context.expressionPlugins,
}).program;
}
catch (e) {
context.onError((0, errors_1.createCompilerError)(45 /* ErrorCodes.X_INVALID_EXPRESSION */, node.loc, undefined, e.message));
return node;
}
const ids = [];
const parentStack = [];
const knownIds = Object.create(context.identifiers);
(0, compiler_core_1.walkIdentifiers)(ast, (node, parent, _, isReferenced, isLocal) => {
if ((0, compiler_core_1.isStaticPropertyKey)(node, parent)) {
return;
}
const needPrefix = isReferenced && canPrefix(node);
if (needPrefix && !isLocal) {
if ((0, compiler_core_1.isStaticProperty)(parent) && parent.shorthand) {
// property shorthand like { foo }, we need to add the key since
// we rewrite the value
;
node.prefix = `${node.name}: `;
}
node.name = rewriteIdentifier(node.name, parent, node);
ids.push(node);
}
else {
// The identifier is considered constant unless it's pointing to a
// local scope variable (a v-for alias, or a v-slot prop)
if (!(needPrefix && isLocal) && !bailConstant) {
;
node.isConstant = true;
}
// also generate sub-expressions for other identifiers for better
// source map support. (except for property keys which are static)
ids.push(node);
}
}, true, // invoke on ALL identifiers
parentStack, knownIds);
// We break up the compound expression into an array of strings and sub
// expressions (for identifiers that have been prefixed). In codegen, if
// an ExpressionNode has the `.children` property, it will be used instead of
// `.content`.
const children = [];
ids.sort((a, b) => a.start - b.start);
ids.forEach((id, i) => {
// range is offset by -1 due to the wrapping parens when parsed
const start = id.start - 1;
const end = id.end - 1;
const last = ids[i - 1];
const leadingText = rawExp.slice(last ? last.end - 1 : 0, start);
if (leadingText.length || id.prefix) {
children.push(leadingText + (id.prefix || ``));
}
const source = rawExp.slice(start, end);
const child = (0, compiler_core_1.createSimpleExpression)(id.name, false, {
source,
start: (0, compiler_core_1.advancePositionWithClone)(node.loc.start, source, start),
end: (0, compiler_core_1.advancePositionWithClone)(node.loc.start, source, end),
}, id.isConstant ? 3 /* ConstantTypes.CAN_STRINGIFY */ : 0 /* ConstantTypes.NOT_CONSTANT */);
if (id.typeAnnotation?.type === 'TSTypeAnnotation') {
child.content = child.loc.source;
}
children.push(child);
if (i === ids.length - 1 && end < rawExp.length) {
children.push(rawExp.slice(end));
}
});
let ret;
if (children.length) {
ret = (0, compiler_core_1.createCompoundExpression)(children, node.loc);
}
else {
ret = node;
ret.constType = bailConstant
? 0 /* ConstantTypes.NOT_CONSTANT */
: 3 /* ConstantTypes.CAN_STRINGIFY */;
}
ret.identifiers = Object.keys(knownIds);
return ret;
}
exports.processExpression = processExpression;
function canPrefix(id) {
// skip whitelisted globals
if (isGloballyWhitelisted(id.name)) {
return false;
}
// special case for webpack compilation
if (id.name === 'require') {
return false;
}
return true;
}
function stringifyExpression(exp) {
if ((0, shared_1.isString)(exp)) {
return exp;
}
else if (exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
return exp.content;
}
else {
return exp.children
.map(stringifyExpression)
.join('');
}
}
exports.stringifyExpression = stringifyExpression;

View File

@@ -0,0 +1,4 @@
import { NodeTransform } from '../transform';
import { TextNode, InterpolationNode, TemplateChildNode } from '@vue/compiler-core';
export declare function isText(node: TemplateChildNode): node is TextNode | InterpolationNode;
export declare const transformInterpolation: NodeTransform;

View File

@@ -0,0 +1,107 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformInterpolation = exports.isText = void 0;
const compiler_core_1 = require("@vue/compiler-core");
// import { CREATE_TEXT } from '../runtimeHelpers'
function isText(node) {
return node.type === 5 /* NodeTypes.INTERPOLATION */ || node.type === 2 /* NodeTypes.TEXT */;
}
exports.isText = isText;
// Merge adjacent text nodes and expressions into a single expression
// e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
const transformInterpolation = (node, context) => {
if (node.type === 0 /* NodeTypes.ROOT */ ||
node.type === 1 /* NodeTypes.ELEMENT */ ||
node.type === 11 /* NodeTypes.FOR */ ||
node.type === 10 /* NodeTypes.IF_BRANCH */) {
// perform the transform on node exit so that all expressions have already
// been processed.
return () => {
const children = node.children;
let currentContainer = undefined;
// let hasText = false
for (let i = 0; i < children.length; i++) {
const child = children[i];
if (isText(child)) {
// hasText = true
for (let j = i + 1; j < children.length; j++) {
const next = children[j];
if (isText(next)) {
if (!currentContainer) {
currentContainer = children[i] = (0, compiler_core_1.createCompoundExpression)([child], child.loc);
}
// merge adjacent text node into current
currentContainer.children.push(` + `, next);
children.splice(j, 1);
j--;
}
else {
currentContainer = undefined;
break;
}
}
}
}
// if (
// !hasText ||
// // if this is a plain element with a single text child, leave it
// // as-is since the runtime has dedicated fast path for this by directly
// // setting textContent of the element.
// // for component root it's always normalized anyway.
// (children.length === 1 &&
// (node.type === NodeTypes.ROOT ||
// (node.type === NodeTypes.ELEMENT &&
// node.tagType === ElementTypes.ELEMENT &&
// // #3756
// // custom directives can potentially add DOM elements arbitrarily,
// // we need to avoid setting textContent of the element at runtime
// // to avoid accidentally overwriting the DOM elements added
// // by the user through custom directives.
// !node.props.find(
// p =>
// p.type === NodeTypes.DIRECTIVE &&
// !context.directiveTransforms[p.name]
// ) &&
// // in compat mode, <template> tags with no special directives
// // will be rendered as a fragment so its children must be
// // converted into vnodes.
// (node.tag !== 'template'))))
// ) {
// return
// }
// pre-convert text nodes into createTextVNode(text) calls to avoid
// runtime normalization.
// for (let i = 0; i < children.length; i++) {
// const child = children[i]
// if (isText(child) || child.type === NodeTypes.COMPOUND_EXPRESSION) {
// const callArgs: CallExpression['arguments'] = []
// // createTextVNode defaults to single whitespace, so if it is a
// // single space the code could be an empty call to save bytes.
// if (child.type !== NodeTypes.TEXT || child.content !== ' ') {
// callArgs.push(child)
// }
// // mark dynamic text with flag so it gets patched inside a block
// if (
// !context.ssr &&
// getConstantType(child, context) === ConstantTypes.NOT_CONSTANT
// ) {
// callArgs.push(
// PatchFlags.TEXT +
// (__DEV__ ? ` /* ${PatchFlagNames[PatchFlags.TEXT]} */` : ``)
// )
// }
// children[i] = {
// type: NodeTypes.TEXT_CALL,
// content: child,
// loc: child.loc,
// codegenNode: createCallExpression(
// context.helper(CREATE_TEXT),
// callArgs
// )
// }
// }
// }
};
}
};
exports.transformInterpolation = transformInterpolation;

View File

@@ -0,0 +1,2 @@
import { NodeTransform } from '../transform';
export declare const transformObjectExpression: NodeTransform;

View File

@@ -0,0 +1,27 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformObjectExpression = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const utils_1 = require("../utils");
const transformObjectExpression = (node, context) => {
// 因为 v-bind without arg 是被 transformElements.ts 直接处理的,没办法在 vBind 中解析处理objectExpression
// 所以 统一在这里拦截处理
return function postTransformObjectExpression() {
node = context.currentNode;
if (!(0, uni_cli_shared_1.isElementNode)(node)) {
return;
}
node.props.forEach((p) => {
if (!(0, uni_cli_shared_1.isDirectiveNode)(p) || !p.exp) {
return;
}
if (p.name === 'bind' || p.name === 'on') {
const newExp = (0, utils_1.rewriteObjectExpression)(p.exp, context);
if (newExp) {
p.exp = newExp;
}
}
});
};
};
exports.transformObjectExpression = transformObjectExpression;

View File

@@ -0,0 +1,10 @@
import { NodeTransform, TransformContext } from '../transform';
import { ExpressionNode, SlotOutletNode } from '@vue/compiler-core';
import { PropsExpression } from '@vue/compiler-core';
export declare const transformSlotOutlet: NodeTransform;
interface SlotOutletProcessResult {
slotName: string | ExpressionNode;
slotProps: PropsExpression | undefined;
}
export declare function processSlotOutlet(node: SlotOutletNode, context: TransformContext): SlotOutletProcessResult;
export {};

View File

@@ -0,0 +1,82 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.processSlotOutlet = exports.transformSlotOutlet = void 0;
const compiler_core_1 = require("@vue/compiler-core");
const compiler_core_2 = require("@vue/compiler-core");
const runtimeHelpers_1 = require("../runtimeHelpers");
const shared_1 = require("@vue/shared");
const transformSlotOutlet = (node, context) => {
if ((0, compiler_core_2.isSlotOutlet)(node)) {
const { children, loc } = node;
const { slotName, slotProps } = processSlotOutlet(node, context);
const slotArgs = [
context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
slotName,
'{}',
'undefined',
'true',
];
let expectedLen = 2;
if (slotProps) {
slotArgs[2] = slotProps;
expectedLen = 3;
}
if (children.length) {
let fn = (0, compiler_core_1.createFunctionExpression)([], children, false, false, loc);
// @ts-expect-error 补充returnType
fn.returnType = `any[]`;
slotArgs[3] = fn;
expectedLen = 4;
}
if (context.scopeId && !context.slotted) {
expectedLen = 5;
}
slotArgs.splice(expectedLen) // remove unused arguments
;
node.codegenNode = (0, compiler_core_1.createCallExpression)(context.helper(runtimeHelpers_1.RENDER_SLOT), slotArgs, loc);
}
};
exports.transformSlotOutlet = transformSlotOutlet;
function processSlotOutlet(node, context) {
let slotName = `"default"`;
let slotProps = undefined;
const nonNameProps = [];
for (let i = 0; i < node.props.length; i++) {
const p = node.props[i];
if (p.type === 6 /* NodeTypes.ATTRIBUTE */) {
if (p.value) {
if (p.name === 'name') {
slotName = JSON.stringify(p.value.content);
}
else {
p.name = (0, shared_1.camelize)(p.name);
nonNameProps.push(p);
}
}
}
else {
if (p.name === 'bind' && (0, compiler_core_2.isStaticArgOf)(p.arg, 'name')) {
if (p.exp)
slotName = p.exp;
}
else {
if (p.name === 'bind' && p.arg && (0, compiler_core_2.isStaticExp)(p.arg)) {
p.arg.content = (0, shared_1.camelize)(p.arg.content);
}
nonNameProps.push(p);
}
}
}
if (nonNameProps.length > 0) {
const { props, directives } = (0, compiler_core_1.buildProps)(node, context, nonNameProps, false, false);
slotProps = props;
if (directives.length) {
context.onError((0, compiler_core_1.createCompilerError)(36 /* ErrorCodes.X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */, directives[0].loc));
}
}
return {
slotName,
slotProps,
};
}
exports.processSlotOutlet = processSlotOutlet;

View File

@@ -0,0 +1,5 @@
import { CompoundExpressionNode } from '@vue/compiler-core';
import { CodegenContext } from '../codegen';
export declare const SLOT_PROPS_NAME = "slotProps";
export declare function isDestructuringSlotProps(isSlot: boolean, params: CompoundExpressionNode): boolean;
export declare function createDestructuringSlotProps(params: CompoundExpressionNode, context: CodegenContext): void;

View File

@@ -0,0 +1,55 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createDestructuringSlotProps = exports.isDestructuringSlotProps = exports.SLOT_PROPS_NAME = void 0;
const shared_1 = require("@vue/shared");
exports.SLOT_PROPS_NAME = 'slotProps';
function isDestructuringSlotProps(isSlot, params) {
if (isSlot && params?.children?.length > 2) {
const firstParam = params.children[0];
const lastParam = params.children[params.children.length - 1];
return ((0, shared_1.isString)(firstParam) &&
firstParam.startsWith('{') &&
(0, shared_1.isString)(lastParam) &&
lastParam.endsWith('}'));
}
return false;
}
exports.isDestructuringSlotProps = isDestructuringSlotProps;
function createDestructuringSlotProps(params, context) {
params.children.forEach((child, index) => {
if (child.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
context.newline();
const content = child.content;
if (isRename(params, index)) {
const originKey = getOriginKey(params.children[index - 1]);
context.push(`const ${content} = ${exports.SLOT_PROPS_NAME}["${originKey}"]`);
}
else if (hasDefaultValue(params, index)) {
const defaultValue = getDefaultValue(params.children[index + 1]);
context.push(`const ${content} = ${exports.SLOT_PROPS_NAME}["${content}"] !== null ? ${exports.SLOT_PROPS_NAME}["${content}"] : ${defaultValue}`);
}
else {
context.push(`const ${content} = ${exports.SLOT_PROPS_NAME}["${content}"]`);
}
}
});
}
exports.createDestructuringSlotProps = createDestructuringSlotProps;
function isRename(params, index) {
const prevChild = params.children[index - 1];
return (0, shared_1.isString)(prevChild) && prevChild.trim().endsWith(':');
}
function getOriginKey(prevChild) {
const originKey = prevChild.substring(0, prevChild.indexOf(':')).trim();
return originKey.startsWith('{') ? originKey.substring(1).trim() : originKey;
}
function hasDefaultValue(params, index) {
const nextChild = params.children[index + 1];
return (0, shared_1.isString)(nextChild) && nextChild.trim().startsWith('=');
}
function getDefaultValue(nextChild) {
const defaultValue = nextChild.trim().substring(1).trim();
return defaultValue.endsWith('}')
? defaultValue.substring(0, defaultValue.length - 1).trim()
: defaultValue;
}

View File

@@ -0,0 +1,2 @@
import { NodeTransform } from '@vue/compiler-core';
export declare const transformStyle: NodeTransform;

View File

@@ -0,0 +1,29 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformStyle = void 0;
const uni_nvue_styler_1 = require("@dcloudio/uni-nvue-styler");
const errors_1 = require("../errors");
// Verify that the template style is in compliance with specifications
const transformStyle = (node, context) => {
if (node.type === 1 /* NodeTypes.ELEMENT */) {
node.props.forEach((p, i) => {
if (p.type === 6 /* NodeTypes.ATTRIBUTE */ && p.name === 'style' && p.value) {
(0, uni_nvue_styler_1.parse)(p.value.content, {
logLevel: 'WARNING',
map: true,
ts: true,
noCode: true,
type: 'uvue',
platform: process.env.UNI_UTS_PLATFORM,
}).then(({ messages }) => {
messages.forEach((message) => {
context.onWarn((0, errors_1.createCompilerError)(100, p.loc, {
100: message.text,
}));
});
});
}
});
}
};
exports.transformStyle = transformStyle;

View File

@@ -0,0 +1,2 @@
import { NodeTransform } from '../transform';
export declare const transformText: NodeTransform;

Some files were not shown because too many files have changed in this diff Show More