前端 uni-app 重写: 9页面 H5

This commit is contained in:
zhiqui
2026-11-15 15:09:37 +08:00
parent 513b53672e
commit ea7c2529e9
24104 changed files with 3667749 additions and 0 deletions
+13
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
+10
View File
@@ -0,0 +1,10 @@
# @dcloudio/types
uni-app 类型提示
## 操作流程
```shell
npm run test
npm run publish:patch
```
+247
View File
@@ -0,0 +1,247 @@
declare namespace string {
/**
* @description 元素上的属性
* @module dom
*/
interface AttrString extends String {}
/**
* @description 元素上某个属性的值
* @module dom
*/
interface AttrValueString extends String {}
/**
* @description 元素全局属性`class`的值
* @module dom
*/
interface ClassString extends String {}
/**
* @description 元素全局属性`id`的值
* @module dom
*/
interface IDString extends String {}
/**
* @description 元素上的事件
* @module dom
*/
interface HTMLEventString extends String {}
/**
* @description CSS颜色的值
* @module dom
*/
interface ColorString extends String {}
/**
* @description 提示common模块 以及js文件路径
* @module vue
*/
interface RequireCommonString extends String {}
/**
* @description 国际化翻译的key值
* @module vue
*/
interface VueI18NKeyString extends String {}
/**
* @description vue默认参数data中的属性名称
* @module vue
*/
interface VueDataString extends String {}
/**
* @description vue组件中ref属性的值
* @module vue
*/
interface VueRefString extends String {}
/**
* @description vuex 中 actions 的名称
* @module vue
*/
interface VuexDispatchString extends String {}
/**
* @description vuex 中 mutations 的名称
* @module vue
*/
interface VuexCommitString extends String {}
/**
* @description vue, nvue, uvue页面文件的文件路径(根据项目自动匹配)
* @module vue
*/
interface PageURIString extends String {}
/**
* @description nvue页面文件的文件路径
* @module vue
*/
interface NPageURIString extends String {}
/**
* @description uvue页面文件的文件路径, 仅在uniappx中生效
* @module uniappx
*/
interface UPageURIString extends String {}
/**
* @description video 组件的 id, 仅在uniappx中生效
* @module uniappx
*/
interface VideoIdString extends String {}
/**
* @description web-view 组件的 id, 仅在uniappx中生效
* @module uniappx
*/
interface WebviewIdString extends String {}
/**
* @description uniCloud db schema中parentKey的值
* @module uniCloud
*/
interface ParentFieldString extends String {}
/**
* @description uniCloud db schema中required数组的值
* @module uniCloud
*/
interface SchemaFieldString extends String {}
/**
* @description uniCloud db schema中validateFunction的值
* @module uniCloud
*/
interface ValidateFunctionString extends String {}
/**
* @description uniCloud 云函数名
* @module uniCloud
*/
interface CloudFunctionString extends String {}
/**
* @description uniCloud 云对象名
* @module uniCloud
*/
interface CloudObjectString extends String {}
/**
* @description uniCloud 数据库集合的名称
* @module uniCloud
*/
interface DBCollectionString extends String {}
/**
* @description uniCloud 数据库字段名称
* @module uniCloud
*/
interface DBFieldString extends String {}
/**
* @description uniCloud 数据库要操作的集合, 要查询的字段
* @module uniCloud
*/
interface JQLString extends String {}
/**
* @description CSS属性的名称
* @module jQuery
*/
interface cssPropertyString extends String {}
/**
* @description CSS某个属性的值
* @module jQuery
*/
interface cssPropertyValueString extends String {}
/**
* @description CSS选择器的名称
* @module jQuery
*/
interface cssSelectorString extends String {}
/**
* @description 任意文件的文件路径
* @module uri
*/
interface URIString extends String {}
/**
* @description css文件的文件路径(后缀为`.css`的文件路径)
* @module uri
*/
interface CSSURIString extends String {}
/**
* @description js文件的文件路径(后缀为`.js`的文件路径)
* @module uri
*/
interface JSURIString extends String {}
/**
* @description html文件的文件路径(后缀为`.html`的文件路径)
* @module uri
*/
interface HTMLURIString extends String {}
/**
* @description markdown文件的文件路径(后缀为`.md`的文件路径)
* @module uri
*/
interface MarkdownURIString extends String {}
/**
* @description js, ts, uts引用文件或模块的文件路径(支持vue,nvue,uvue中script标签内容), 例: `import xxx from 'xxx'`
* @module uri
*/
interface ScriptImportURIString extends String {}
/**
* @description css文件可以引用的文件的文件路径, 后缀为`[".css"]`的文件路径 例: `@import url('xxx.css')`
* @module uri
*/
interface CssImportURIString extends String {}
/**
* @description scss文件可以引用的文件的文件路径, 后缀为`[".scss", ".css"]`的文件路径, 例: `@import 'xxx.scss'`
* @module uri
*/
interface ScssImportURIString extends String {}
/**
* @description less文件可以引用的文件的文件路径, 后缀为`[".less", ".css"]`的文件路径, 例: `@import 'xxx.less'`
* @module uri
*/
interface LessImportURIString extends String {}
/**
* @description 字体文件的文件路径
* @module uri
*/
interface FontURIString extends String {}
/**
* @description 图片文件的文件路径
* @module uri
*/
interface ImageURIString extends String {}
/**
* @description 音频文件的文件路径
* @module uri
*/
interface AudioURIString extends String {}
/**
* @description 视频文件的文件路径
* @module uri
*/
interface VideoURIString extends String {}
}
+1
View File
@@ -0,0 +1 @@
/// <reference path="./HBuilderX.d.ts" />
+2
View File
@@ -0,0 +1,2 @@
/// <reference path="../hbuilder-x/index.d.ts" />
/// <reference path="./plus.d.ts" />
File diff suppressed because it is too large Load Diff
+2
View File
@@ -0,0 +1,2 @@
/// <reference path="./uni-app/index.d.ts" />
/// <reference path="./html5plus/plus.d.ts" />
+30
View File
@@ -0,0 +1,30 @@
{
"name": "@dcloudio/types",
"version": "3.4.31",
"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",
"publish:patch": "npm version patch && npm publish",
"publish:minor": "npm version minor && npm publish",
"publish:major": "npm version major && npm publish",
"postpublish": "npx cnpm sync @dcloudio/types"
},
"author": "fxy060608",
"license": "Apache-2.0",
"devDependencies": {
"@definitelytyped/dtslint": "^0.0.115",
"miniprogram-api-typings": "4.1.2",
"ts-morph": "^17.0.1",
"tslint": "^5.14.0",
"typescript": "5.0.4",
"vue": "2.6"
},
"packageManager": "pnpm@9.5.0+sha512.140036830124618d624a2187b50d04289d5a087f326c9edfc0ccd733d76c4f52c3a313d4fc148794a2a9d81553016004e6742e8cf850670268a7387fc220c903"
}
+220
View File
@@ -0,0 +1,220 @@
declare namespace App {
interface ReferrerInfo {
/**
* 来源小程序或公众号或App的 appId
*
* 以下场景支持返回 referrerInfo.appId:
* - 1020(公众号 profile 页相关小程序列表): appId
* - 1035(公众号自定义菜单):来源公众号 appId
* - 1036(App 分享消息卡片):来源应用 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;
+9
View File
@@ -0,0 +1,9 @@
/// <reference path="../hbuilder-x/index.d.ts" />
/// <reference path="./uni-cloud-client/index.d.ts" />
/**
* uniCloud 实例变量
*
* 文档: [https://uniapp.dcloud.net.cn/uniCloud/](https://uniapp.dcloud.net.cn/uniCloud/)
*/
declare const uniCloud: UniCloudNamespace.UniCloud;
+7
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;
+11
View File
@@ -0,0 +1,11 @@
/// <reference path="../hbuilder-x/index.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;
+718
View File
@@ -0,0 +1,718 @@
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 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;
/**
* 自定义图片,显示图片长宽比为 1:1
*/
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 OnShareTimelineOptions extends OnShareChatOptions {}
interface ShareTimelineContent extends Omit<ShareChatContent, 'content'> {}
interface ShareChatContent {
/**
* 自定义标题,即朋友圈列表页上显示的标题。默认值:当前小程序名称
*/
title?: string;
/**
* 自定义页面路径中携带的参数,如 path?a=1&b=2 的 “?” 后面部分。默认值:当前页面路径携带的参数
*/
query?: string;
/**
* 自定义图片路径,可以是本地文件或者网络图片。支持 PNG 及 JPG,显示图片长宽比是 1:1。默认值:小程序 Logo
*/
imageUrl?: string;
/**
* 转发的路径
*/
path?: string;
/**
* 分享到小红书站外的截图字段 (用于站外 h5 落地页展示,不传默认容器截取栈顶页面)
*/
externalImageUrl?: string;
/**
* 好友分享的内容描述 (默认取小程序描述)
*/
content?: string;
/**
* 如果该参数存在,则以 resolve 结果为准,如果三秒内不 resolve,分享会使用上面传入的默认
*/
promise?: Promise<Omit<ShareChatContent, 'promise'>>;
/**
* 分享成功回调(回调中无分享信息)
*/
success?: () => void;
/**
* 分享失败回调(回调中无失败信息)
*/
fail?: () => void;
/**
* 分享完成回调
*/
complete?: () => void;
}
interface OnShareChatOptions {
/**
* 转发事件来源。button:页面内转发按钮;menu:右上角转发菜单
*/
from?: 'button' | 'menu';
/**
* 当前页面的 pageId
*/
pageId?: string;
/**
* 分享类型
*/
shareType?: string;
/**
* 如果 from 值是 button,则 target 是触发这次转发事件的 button,否则为 undefined
*/
target?: Record<string, any>;
}
interface OnCopyUrlOptions {
/**
* 转发事件来源。button:页面内转发按钮;menu:右上角转发菜单
*/
from?: 'button' | 'menu';
/**
* 当前页面的 pageId
*/
pageId?: string;
/**
* 分享类型
*/
shareType?: string;
}
interface CopyUrlContent {
/**
* 转发的路径 (默认为当前页面路径)
*/
path?: string;
/**
* 自定义页面路径中携带的参数,如 path?a=1&b=2 的 “?” 后面部分 (默认为当前页面路径携带的参数)
*/
query?: string;
/**
* 分享到小红书站外的截图字段 (用于站外 h5 落地页展示,不传默认容器截取栈顶页面)
*/
externalImageUrl?: string;
/**
* 分享成功回调(回调中无分享信息)
*/
success?: () => void;
/**
* 分享失败回调(回调中无失败信息)
*/
fail?: () => void;
/**
* 分享完成回调
*/
complete?: () => void;
}
interface UploadDouyinVideoOptions {
target: {
id: string;
dataset: Record<string, any>;
offsetTop: number;
offsetLeft: number;
};
from: 'anchor' | 'menu' | 'button' | 'mission_publish' | 'mission_select';
webViewUrl: string;
}
interface UploadDouyinVideoSuccessCallback {
videoId?: string;
taskResult?: Array<{
taskId?: string;
completed?: boolean;
successCount?: number;
failCount?: number;
isValid?: boolean;
errMsg?: string;
errNo?: number;
}>;
errMsg?: string;
}
interface UploadDouyinVideoFailCallback {
errNo?: number;
errMsg?: string;
}
interface UploadDouyinVideoContent {
videoPath?: string;
taskIds?: string[];
extra: {
anchor?: {
anchorType?: 'none' | 'app';
title?: string;
path?: string;
};
createChallenge?: boolean;
};
titleConfig?: {
title?: string;
mentionMarkers?: Array<{ start?: number; openId?: string }>;
hashtagMarkers?: Array<{ start?: number; hashtag?: string }>;
};
stickersConfig?: {
text?: Array<{
text: string;
color?: string;
fontSize?: number;
scale?: number;
x?: number;
y?: number;
}>;
hashtag?: Array<{ name: string; x?: number; y?: number }>;
mention?: Array<{ openId: string }>;
custom?: Array<{
path: string;
scale?: number;
rotate?: number;
x?: number;
y?: number;
}>;
};
success?: (callback: UploadDouyinVideoSuccessCallback) => void;
fail?: (callback: UploadDouyinVideoFailCallback) => void;
complete?: (callback: UploadDouyinVideoSuccessCallback | UploadDouyinVideoFailCallback) => void;
}
interface LiveMountSuccessCallback {
errMsg?: string;
}
interface LiveMountFailCallback {
errNo?: number;
errMsg?: string;
}
interface LiveMountOptions {
webViewUrl: string;
}
interface LiveMountContent {
title?: string;
path?: string;
success?: (callback: LiveMountSuccessCallback) => void;
fail?: (callback: LiveMountFailCallback) => void;
complete?: (callback: LiveMountSuccessCallback | LiveMountFailCallback) => void;
}
interface PageInstance<D extends AnyObject = any, T extends AnyObject = any>
extends PageInstanceBaseProps<D> {
/**
* 生命周期回调 监听页面初始化
*
* 页面初始化时触发。一个页面只会调用一次,可以在 onInit 的参数中获取打开当前页面路径中的参数。
* @param query 打开当前页面路径中的参数
*
* 文档: [https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle](https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle)
* @uniPlatform {
* "app": {
* "android": {
* "osVer": "x",
* "uniVer": "x",
* "unixVer": "x"
* },
* "ios": {
* "osVer": "x",
* "uniVer": "x",
* "unixVer": "x"
* }
* },
* "mp": {
* "weixin": {
* "hostVer": "x",
* "uniVer": "x",
* "unixVer": "x"
* },
* "alipay": {
* "hostVer": "x",
* "uniVer": "x",
* "unixVer": "x"
* },
* "baidu": {
* "hostVer": ">=3.160.12",
* "uniVer": ">=3.1.0",
* "unixVer": "x"
* },
* "toutiao": {
* "hostVer": "x",
* "uniVer": "x",
* "unixVer": "x"
* },
* "lark": {
* "hostVer": "x",
* "uniVer": "x",
* "unixVer": "x"
* },
* "qq": {
* "hostVer": "x",
* "uniVer": "x",
* "unixVer": "x"
* },
* "kuaishou": {
* "hostVer": "x",
* "uniVer": "x",
* "unixVer": "x"
* },
* "jd": {
* "hostVer": "x",
* "uniVer": "x",
* "unixVer": "x"
* },
* "360": {
* "hostVer": "x",
* "uniVer": "x",
* "unixVer": "x"
* }
* },
* "quickapp": {
* "uniVer": "x",
* "unixVer": "x"
* },
* "web": {
* "uniVer": "x",
* "unixVer": "x"
* }
* }
*/
onInit?(query?: AnyObject): void;
/**
* 生命周期回调 监听页面加载
*
* 页面加载时触发。一个页面只会调用一次,可以在 onLoad 的参数中获取打开当前页面路径中的参数。
* @param query 打开当前页面路径中的参数
*
* 文档: [https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle](https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle)
*/
onLoad?(query?: AnyObject): void;
/**
* 生命周期回调 监听页面显示
*
* 页面显示/切入前台时触发。
*
* 文档: [https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle](https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle)
*/
onShow?(): void;
onPageShow?(): void;
/**
* 生命周期回调 监听页面初次渲染完成
*
* 页面初次渲染完成时触发。一个页面只会调用一次,代表页面已经准备妥当,可以和视图层进行交互。
*
* 文档: [https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle](https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle)
*/
onReady?(): void;
/**
* 生命周期回调 监听页面隐藏
*
* 页面隐藏/切入后台时触发。 如 `navigateTo` 或底部 `tab` 切换到其他页面,应用切入后台等。
*
* 文档: [https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle](https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle)
*/
onHide?(): void;
onPageHide?(): void;
/**
* 生命周期回调 监听页面卸载
*
* 页面卸载时触发。如 `redirectTo` 或 `navigateBack` 到其他页面时。
*
* 文档: [https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle](https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle)
*/
onUnload?(): void;
/**
* 监听用户下拉动作
* - 需要在 `pages.json` 的页面配置中开启 `enablePullDownRefresh` 。
* - 可以通过 `uni.startPullDownRefresh` 触发下拉刷新,调用后触发下拉刷新动画,效果与用户手动下拉刷新一致。
* - 当处理完数据刷新后,`uni.stopPullDownRefresh` 可以停止当前页面的下拉刷新。
*
* 文档: [https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle](https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle)
*/
onPullDownRefresh?(): void;
/**
* 页面上拉触底事件的处理函数
* - 可以在 `pages.json` 的页面配置中设置触发距离 `onReachBottomDistance` 。
* - 在触发距离内滑动期间,本事件只会被触发一次。
*
* 文档: [https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle](https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle)
*/
onReachBottom?(): void;
/**
* 支付宝小程序点击标题时触发
* 文档: [https://opendocs.alipay.com/mini/framework/page-detail#onTitleClick()](https://opendocs.alipay.com/mini/framework/page-detail#onTitleClick())
*/
onTitleClick?(): void;
/**
* 在抖音直播中挂载小程序锚点时触发
* 文档: [https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/develop/api/open-interface/retweet/live-mount/live-param](https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/develop/api/open-interface/retweet/live-mount/live-param)
*/
onLiveMount?(options: LiveMountOptions): LiveMountContent | Promise<LiveMountContent>;
/**
* 发布抖音视频时触发
* 文档: [https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/develop/api/open-interface/retweet/video-publish/upload-param](https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/develop/api/open-interface/retweet/video-publish/upload-param)
*/
onUploadDouyinVideo?(
options: UploadDouyinVideoOptions
): UploadDouyinVideoContent | Promise<UploadDouyinVideoContent>;
/**
* 用户点击右上角转发
*
* 监听用户点击页面内转发按钮(`<button>` 组件 `open-type="share"`)或右上角菜单“转发”按钮的行为,并自定义转发内容。
* @param options 分享发起来源参数
* @return 转发内容
*
* 文档: [https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle](https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle)
*/
onShareAppMessage?(
options: ShareAppMessageOption
): CustomShareContent | Promise<Omit<CustomShareContent, "promise">>;
/**
* 用户点击右上角转发到朋友圈
*
* 监听右上角菜单“分享到朋友圈”按钮的行为,并自定义发享内容。
*
* 文档: [https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle](https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle)
*/
onShareTimeline?(options: OnShareTimelineOptions): ShareTimelineContent;
/**
* 用户点击右上角收藏
*
* 监听用户点击右上角菜单“收藏”按钮的行为,并自定义收藏内容。
*
* 文档: [https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle](https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle)
*/
onAddToFavorites?(options: AddToFavoritesOption): CustomFavoritesContent;
/**
* 页面滚动触发事件的处理函数
*
* 监听用户滑动页面事件。
* @param options 页面滚动参数
*
* 文档: [https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle](https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle)
*/
onPageScroll?(options: PageScrollOption): void;
/**
* 页面尺寸改变时触发
* @param options 页面滚动参数
*
* 文档: [https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle](https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle)
* @uniPlatform {
* "App": {
* "baidu": {
* "hostVer": ">=3.160.12",
* "uniVer": ">=3.1.0",
* "unixVer": "x"
* }
* }
* }
*/
onResize?(options: ResizeOption): void;
/**
* 当前是 tab 页时,点击 tab 时触发
* @param options tab 点击参数
*
* 文档: [https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle](https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle)
*/
onTabItemTap?(options: TabItemTapOption): void;
/**
* 监听原生标题栏按钮点击事件
* @param options tab 点击参数
*
* 文档: [https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle](https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle)
*/
onNavigationBarButtonTap?(options: NavigationBarButtonTapOption): void;
/**
* 监听页面返回
* @param options tab 点击参数
* @return 返回 `true` 时阻止页面返回
*
* 文档: [https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle](https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle)
*/
onBackPress?(options: BackPressOption): any;
/**
* 监听原生标题栏搜索输入框输入内容变化事件
*
* 文档: [https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle](https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle)
*/
onNavigationBarSearchInputChanged?(
event: NavigationBarSearchInputEvent
): void;
/**
* 监听原生标题栏搜索输入框搜索事件,用户点击软键盘上的“搜索”按钮时触发。
*
* 文档: [https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle](https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle)
*/
onNavigationBarSearchInputConfirmed?(
event: NavigationBarSearchInputEvent
): void;
/**
* 监听原生标题栏搜索输入框点击事件
*
* 文档: [https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle](https://uniapp.dcloud.net.cn/tutorial/page.html#lifecycle)
*/
onNavigationBarSearchInputClicked?(): void;
/**
* 小红书特有生命周期:监听右上角菜单“分享到微信群组”按钮的行为,并自定义分享内容。
*
* 文档: [https://miniapp.xiaohongshu.com/docs?path=/docs/frame/Page#onShareChat](https://miniapp.xiaohongshu.com/docs?path=/docs/frame/Page#onShareChat)
*/
onShareChat?(options: OnShareChatOptions): ShareChatContent;
/**
* 小红书特有生命周期:监听右上角菜单“复制链接”按钮的行为,并自定义分享内容。
*
* 文档:[https://miniapp.xiaohongshu.com/doc/DC686827#anchorId-oncopyurl](https://miniapp.xiaohongshu.com/doc/DC686827#anchorId-oncopyurl)
*/
onCopyUrl?(options: OnCopyUrlOptions): CopyUrlContent;
}
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;
@@ -0,0 +1,252 @@
declare namespace UniCloudNamespace {
interface CurrentUserInfo {
/**
* 当前用户uid
*/
uid: string;
/**
* 当前用户角色列表
*/
role: any[];
/**
* 当前用户权限列表
*/
permission: any[];
}
interface UniCloudOptions {
/**
* 选择服务供应商
* - tencent: 选择腾讯云作为服务商
* - aliyun: 选择阿里云作为服务商
*/
provider: 'tencent' | 'aliyun';
/**
* 服务空间ID
*/
spaceId: string;
/**
* 服务空间对应的clientSecret
*/
clientSecret?: string;
/**
* 服务空间地址
*/
endpoint?: string;
}
interface UniError {
/**
* 错误模块名
*/
errSubject?: string;
/**
* 错误码
*/
errCode: number | string;
/**
* 错误信息
*/
errMsg: string;
/**
* 请求id方便排错
*/
requestId?: string;
/**
* 错误详情
*/
detail?: any;
/**
* 上级错误
*/
cause?: UniError;
}
interface CallFunctionResult {
/**
* 云函数执行结果
*/
result: any;
/**
* 请求序列号,用于错误排查
*/
requestId?: string;
}
enum SECRET_TYPE {
/**
* 不加密
*/
none = 'none',
/**
* 仅请求参数加密
*/
request = 'request',
/**
* 仅响应结果加密
*/
response = 'response',
/**
* 请求响应均加密
*/
both = 'both'
}
interface CallFunctionOptions {
/**
* 云函数名
*/
name: string | string.CloudFunctionString;
/**
* 传递给云函数的参数
*/
data?: any;
/**
* 安全网络类型
* - none:不加密
* - request:仅请求参数加密
* - response:仅响应结果加密
* - both:请求响应均加密
*/
secretType?: keyof typeof SECRET_TYPE;
/**
* 成功返回的回调函数
*/
success?: (result: CallFunctionResult) => void;
/**
* 失败返回的回调函数
*/
fail?: (result: any) => void;
/**
* 结束的回调函数(调用成功、失败都会执行
*/
complete?: (result: CallFunctionResult) => void;
}
interface ImportObjectLoadingOptions {
/**
* loading界面文字
*/
text?: string;
/**
* loading是否显示透明遮罩
*/
mask?: boolean;
}
interface ImportObjectErrorOptions {
/**
* 错误提示类型,modal | toast
*/
type?: 'modal' | 'toast';
/**
* 是否显示重试按钮,type为modal时生效
*/
retry?: boolean;
}
interface ParseSystemErrorOptions {
/**
* 云对象名
*/
objectName: string;
/**
* 调用的方法名
*/
methodName: string;
/**
* 参数
*/
params: Array<any>;
/**
* 错误码
*/
errCode: string | number;
/**
* 错误信息
*/
errMsg: string;
}
interface ParsedSystemErrorResult {
errMsg: string;
}
interface ImportObjectOptions {
/**
* 是否移除自动展示的ui
*/
customUI?: boolean;
/**
* loading界面配置
*/
loadingOptions?: ImportObjectLoadingOptions;
/**
* 错误提示配置
*/
errorOptions?: ImportObjectErrorOptions;
/**
* 使用安全网络的方法及安全网络类型
*/
secretMethods?: Record<string, keyof typeof SECRET_TYPE>;
/**
* 转化云对象内未捕获的错误或客户端网络错误
*/
parseSystemError?: (options: ParseSystemErrorOptions) => Promise<ParsedSystemErrorResult> | ParsedSystemErrorResult;
}
interface InitSecureNetworkByWeixinOptions {
/**
* 是否握手并自动调用uni-id-co的微信登录,默认仅调用uni-id-co的secureNetworkHandshakeByWeixin不调用微信登录
*/
callLoginByWeixin?: boolean;
/**
* 用户openid,传此参数时不会调用uni-id-co的任何方法
*/
openid?: string;
}
interface InitSecureNetworkByWeixinResponse {
code?: string;
}
interface UniCloud {
/** 用于快速开发datacom规范的组件 */
mixinDatacom: any;
/**
* 服务空间初始化,返回uniCloud实例
*
* 文档: [https://uniapp.dcloud.io/uniCloud/init](https://uniapp.dcloud.io/uniCloud/init)
*/
init(options: UniCloudOptions): UniCloud;
/**
* 设置自定义clientInfo信息
*
* 文档: [https://doc.dcloud.net.cn/uniCloud/client-sdk.html#set-custom-client-info](https://doc.dcloud.net.cn/uniCloud/client-sdk.html#set-custom-client-info)
*/
setCustomClientInfo(options: object): void;
/**
* 调用云函数
*
* 文档: [https://uniapp.dcloud.io/uniCloud/cf-functions?id=clientcallfunction](https://uniapp.dcloud.io/uniCloud/cf-functions?id=clientcallfunction)
*/
callFunction(options: CallFunctionOptions): Promise<any>;
/**
* 引用云对象
*
* 文档: [https://uniapp.dcloud.io/uniCloud/cloud-obj](https://uniapp.dcloud.io/uniCloud/cloud-obj)
*/
importObject(objectName: string | string.CloudObjectString, importObjectOptions?: ImportObjectOptions): any;
/**
* 获取当前用户缓存在token内的信息
*
* 文档: [https://uniapp.dcloud.io/uniCloud/client-sdk.html#client-getcurrentuserinfo](https://uniapp.dcloud.io/uniCloud/client-sdk.html#client-getcurrentuserinfo)
*/
getCurrentUserInfo(): CurrentUserInfo;
/**
* 微信小程序安全网络初始化
*
* 文档: [https://uniapp.dcloud.io/uniCloud/client-sdk.html#client-getcurrentuserinfo](https://uniapp.dcloud.io/uniCloud/client-sdk.html#init-secure-network-by-weixin)
*/
initSecureNetworkByWeixin(options?: InitSecureNetworkByWeixinOptions): Promise<InitSecureNetworkByWeixinResponse>;
}
}
@@ -0,0 +1,54 @@
declare namespace UniCloudNamespace {
interface UserInfo {
/**
* 用户在uniCloud的唯一ID
*/
uid: string;
/**
* 自定义登录的用户ID
*/
customUserId: string;
}
interface Auth {
/**
* 任何方式登录成功后,可以调用 getUserInfo 获得用户的身份信息
*
* 文档: [https://uniapp.dcloud.io/uniCloud/authentication?id=authgetuserinfo](https://uniapp.dcloud.io/uniCloud/authentication?id=authgetuserinfo)
*/
getUserInfo(): UserInfo;
/**
* 开发者可以通过 getLoginState() 来获取当前的登录状态,调用 getLoginState() 后,SDK 会识别本地是否有登录状态,如果有,则会尝试刷新登录状态,若刷新登录状态成功,则会返回新的登录状态,否则返回 undefined
*
* 文档: [https://uniapp.dcloud.io/uniCloud/authentication?id=authgetloginstate](https://uniapp.dcloud.io/uniCloud/authentication?id=authgetloginstate)
*/
getLoginState(): void;
/**
* 进行匿名登录
*
* 文档: [https://uniapp.dcloud.io/uniCloud/authentication?id=authsigninanonymously](https://uniapp.dcloud.io/uniCloud/authentication?id=authsigninanonymously)
*/
signInAnonymously(): void;
/**
* 进行自定义登录
*
* 文档: [https://uniapp.dcloud.io/uniCloud/authentication?id=authsigninwithticket](https://uniapp.dcloud.io/uniCloud/authentication?id=authsigninwithticket)
*/
signInWithTicket(): void;
/**
* 进行自定义登录
*
* 文档: [https://uniapp.dcloud.io/uniCloud/authentication?id=authshouldrefreshaccesstoken](https://uniapp.dcloud.io/uniCloud/authentication?id=authshouldrefreshaccesstoken)
*/
shouldRefreshAccessToken(callback: (result: any) => void): void;
}
interface UniCloud {
/**
* 获取登录对象
*
* 文档: [https://uniapp.dcloud.io/uniCloud/authentication?id=custom-auth](https://uniapp.dcloud.io/uniCloud/authentication?id=custom-auth)
*/
customAuth(): Auth;
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,58 @@
declare namespace UniCloudNamespace {
interface UniCloudResponseEvent {
type: 'clientdb' | 'cloudobject' | 'cloudfunction';
content: any;
}
interface UniCloudNeedLoginEvent {
errCode: string | number;
errMsg: string;
uniIdRedirectUrl: string;
}
interface UniCloudRefreshTokenEvent {
token: string;
tokenExpired: number;
}
interface UniCloud {
/** 事件回调 */
on(eventName: string, callback: (result: any) => void): void;
/**
* 监听云函数、云对象、clientDB的响应
*
* 文档: [https://uniapp.dcloud.io/uniCloud/client-sdk.html#on-response](https://uniapp.dcloud.io/uniCloud/client-sdk.html#on-response)
*/
onResponse(callback: (result?: UniCloudResponseEvent) => void): void;
/**
* 移除监听云函数、云对象、clientDB的响应
*
* 文档: [https://uniapp.dcloud.io/uniCloud/client-sdk.html#off-response](https://uniapp.dcloud.io/uniCloud/client-sdk.html#off-response)
*/
offResponse(callback: (result?: UniCloudResponseEvent) => void): void;
/**
* 监听需要登录事件
*
* 文档: [https://uniapp.dcloud.io/uniCloud/client-sdk.html#on-need-login](https://uniapp.dcloud.io/uniCloud/client-sdk.html#on-need-login)
*/
onNeedLogin(callback: (result?: UniCloudNeedLoginEvent) => void): void;
/**
* 移除监听需要登录事件
*
* 文档: [https://uniapp.dcloud.io/uniCloud/client-sdk.html#off-need-login](https://uniapp.dcloud.io/uniCloud/client-sdk.html#off-need-login)
*/
offNeedLogin(callback: (result?: UniCloudNeedLoginEvent) => void): void;
/**
* 监听token刷新事件
*
* 文档: [https://uniapp.dcloud.io/uniCloud/client-sdk.html#on-refresh-token](https://uniapp.dcloud.io/uniCloud/client-sdk.html#on-refresh-token)
*/
onRefreshToken(callback: (result?: UniCloudRefreshTokenEvent) => void): void;
/**
* 移除监听token刷新事件
*
* 文档: [https://uniapp.dcloud.io/uniCloud/client-sdk.html#off-refresh-token](https://uniapp.dcloud.io/uniCloud/client-sdk.html#off-refresh-token)
*/
offRefreshToken(callback: (result: UniCloudRefreshTokenEvent) => void): void;
}
}
@@ -0,0 +1,7 @@
/// <reference path="custom-auth.d.ts" />
/// <reference path="database.d.ts" />
/// <reference path="event.d.ts" />
/// <reference path="interceptor.d.ts" />
/// <reference path="sse-channel.d.ts" />
/// <reference path="storage.d.ts" />
/// <reference path="websocket.d.ts" />
@@ -0,0 +1,52 @@
declare namespace UniCloudNamespace {
interface Interceptor {
invoke?: (result: any) => void;
success?: (result: any) => void;
fail?: (result: any) => void;
complete?: (result: any) => void;
}
interface BaseObjectInterceptorArgs {
objectName: string;
methodName: string;
params: string;
}
interface SuccessObjectInterceptorArgs extends BaseObjectInterceptorArgs {
result: any;
}
interface FailObjectInterceptorArgs extends BaseObjectInterceptorArgs {
error: UniError;
}
type CompleteObjectInterceptorArgs = SuccessObjectInterceptorArgs | FailObjectInterceptorArgs;
interface ObjectInterceptor {
invoke?: (result: BaseObjectInterceptorArgs) => void;
success?: (result: SuccessObjectInterceptorArgs) => void;
fail?: (result: FailObjectInterceptorArgs) => void;
complete?: (result: CompleteObjectInterceptorArgs) => void;
}
interface UniCloud {
/**
* 添加拦截器
*
* 文档: [https://uniapp.dcloud.io/uniCloud/client-sdk.html#add-interceptor](https://uniapp.dcloud.io/uniCloud/client-sdk.html#add-interceptor)
*/
addInterceptor(apiName: string, interceptor: Interceptor): void;
/**
* 移除拦截器
*
* 文档: [https://uniapp.dcloud.io/uniCloud/client-sdk.html#remove-interceptor](https://uniapp.dcloud.io/uniCloud/client-sdk.html#remove-interceptor)
*/
removeInterceptor(apiName: string, interceptor?: Interceptor): void;
/**
* 拦截云对象请求
*
* 文档: [https://uniapp.dcloud.io/uniCloud/client-sdk.html#intercept-object](https://uniapp.dcloud.io/uniCloud/client-sdk.html#intercept-object)
*/
interceptObject(interceptor: ObjectInterceptor): void;
}
}
@@ -0,0 +1,110 @@
declare namespace UniCloudNamespace {
class SSEChannel {
constructor();
/**
* 开启消息通道
*
* 文档:[https://uniapp.dcloud.net.cn/uniCloud/sse-channel.html#channel-open](https://uniapp.dcloud.net.cn/uniCloud/sse-channel.html#channel-open)
*/
open: () => Promise<void>;
/**
* 关闭消息通道
*
* 文档:[https://uniapp.dcloud.net.cn/uniCloud/sse-channel.html#channel-close](https://uniapp.dcloud.net.cn/uniCloud/sse-channel.html#channel-close)
*/
close: () => void;
/**
* 添加通道开启事件监听器
*/
on(event: 'open', callback: () => any): void;
/**
* 添加消息接收事件监听器
*/
on(event: 'message', callback: (message?: any) => any): void;
/**
* 添加通道消息完毕事件监听器
*/
on(event: 'end', callback: (message?: any) => any): void;
/**
* 添加通道关闭事件监听器
*/
on(event: 'close', callback: () => any): void;
/**
* 添加通道错误事件监听器
*/
on(event: 'error', callback: (err?: any) => any): void;
/**
* 添加通道开启事件监听器
*/
addListener(event: 'open', callback: () => any): void;
/**
* 添加消息接收事件监听器
*/
addListener(event: 'message', callback: (message?: any) => any): void;
/**
* 添加通道消息完毕事件监听器
*/
addListener(event: 'end', callback: (message?: any) => any): void;
/**
* 添加通道关闭事件监听器
*/
addListener(event: 'close', callback: () => any): void;
/**
* 添加通道错误事件监听器
*/
addListener(event: 'error', callback: (err?: any) => any): void;
/**
* 移除通道开启事件监听器
*/
off(event: 'open', callback: () => any): void;
/**
* 移除消息接收事件监听器
*/
off(event: 'message', callback: (message?: any) => any): void;
/**
* 移除通道消息完毕事件监听器
*/
off(event: 'end', callback: (message?: any) => any): void;
/**
* 移除通道关闭事件监听器
*/
off(event: 'close', callback: () => any): void;
/**
* 移除通道错误事件监听器
*/
off(event: 'error', callback: (err?: any) => any): void;
/**
* 移除通道开启事件监听器
*/
removeListener(event: 'open', callback: () => any): void;
/**
* 移除消息接收事件监听器
*/
removeListener(event: 'message', callback: (message?: any) => any): void;
/**
* 移除通道消息完毕事件监听器
*/
removeListener(event: 'end', callback: (message?: any) => any): void;
/**
* 移除通道关闭事件监听器
*/
removeListener(event: 'close', callback: () => any): void;
/**
* 移除通道错误事件监听器
*/
removeListener(event: 'error', callback: (err?: any) => any): void;
/**
* 移除指定事件的所有监听器
*/
removeAllListener(event: 'open' | 'message' | 'end' | 'close' | 'error'): void;
}
interface UniCloud {
/**
* 云函数请求中的中间状态通知通道类
*
* 文档:[https://uniapp.dcloud.net.cn/uniCloud/sse-channel.html#create-sse-channel](https://uniapp.dcloud.net.cn/uniCloud/sse-channel.html#create-sse-channel)
*/
SSEChannel: SSEChannel;
}
}
@@ -0,0 +1,324 @@
declare namespace UniCloudNamespace {
interface GeneralCallbackResult {
/**
* 状态码,操作成功则不返回
*/
errCode: string;
/**
* 错误信息
*/
errMsg: string;
}
interface OnUploadProgressResult {
/**
* 已上传大小
*/
loaded: number;
/**
* 上传文件总大小
*/
total: number;
}
interface UploadFileResult {
/**
* 文件唯一 ID,用来访问文件,建议存储起来
*/
fileID: string;
}
interface UploadFileOptions {
/**
* 文件的绝对路径,包含文件名。例如 foo/bar.jpg、foo/bar/baz.jpg 等
*/
cloudPath: string;
/**
* 要上传的文件对象
*/
filePath: string;
/**
* 阿里云是否以cloudPath作为实际存储路径,默认为false(否)
*/
cloudPathAsRealPath?: boolean;
/**
* 上传进度回调
*/
onUploadProgress?: (result: OnUploadProgressResult) => void;
/**
* 成功返回的回调函数
*/
success?: (result: UploadFileResult) => void;
/**
* 失败返回的回调函数
*/
fail?: (result: GeneralCallbackResult) => void;
/**
* 结束的回调函数(调用成功、失败都会执行
*/
complete?: (result: UploadFileResult) => void;
}
interface DeleteFileItem {
/**
* 云端fileID
*/
fileID: string;
/**
* 状态码,操作成功则不返回
*/
code: string;
}
interface DeleteFileResult {
/**
* 要删除的文件 ID 组成的数组
*/
fileList: DeleteFileItem[];
}
interface DeleteFileOptions {
/**
* 文件ID组成的数组
*/
fileList: any[];
/**
* 成功返回的回调函数
*/
success?: (result: DeleteFileResult) => void;
/**
* 失败返回的回调函数
*/
fail?: (result: GeneralCallbackResult) => void;
/**
* 结束的回调函数(调用成功、失败都会执行
*/
complete?: (result: DeleteFileResult) => void;
}
interface GetTempFileURLItem {
/**
* 文件 ID
*/
fileID: string;
/**
* 状态码,操作成功则为 SUCCESS
*/
code: string;
/**
* 文件访问链接
*/
tempFileURL: string;
}
interface GetTempFileURLResult {
/**
* 存储下载链接的数组
*/
fileList: any[];
}
interface GetTempFileURLOptions {
/**
* 文件ID组成的数组
*/
fileList: any[];
/**
* 成功返回的回调函数
*/
success?: (result: GetTempFileURLResult) => void;
/**
* 失败返回的回调函数
*/
fail?: (result: GeneralCallbackResult) => void;
/**
* 结束的回调函数(调用成功、失败都会执行
*/
complete?: (result: GetTempFileURLResult) => void;
}
interface ChooseAndUploadFileSuccessCallbackResult {
/**
* 错误信息
*/
errMsg: string;
/**
* 临时文件路径列表
*/
tempFilePaths: any[];
/**
* 文件列表,每一项是一个 File 对象
*/
tempFiles: any[];
}
interface ChooseAndUploadFileOnUploadProgressCallbackResult {
/**
* 触发当前上传进度回调的文件序号
*/
index: number;
/**
* 已上传大小
*/
loaded: number;
/**
* 总大小
*/
total: number;
/**
* 临时文件路径
*/
tempFilePath: string;
/**
* 文件对象
*/
tempFile: any;
}
interface ChooseAndUploadFileOnChooseFileCallbackResult {
/**
* 错误信息
*/
errMsg: string;
/**
* 临时文件路径列表
*/
tempFilePaths: any[];
/**
* 文件列表,每一项是一个 File 对象
*/
tempFiles: any[];
}
interface ChooseAndUploadFileOptions {
/**
* 文件类型
* - image: 图片
* - video: 视频
* - all: 任意文件
*/
type: 'image' | 'video' | 'all';
/**
* 文件数量
*/
count?: number;
/**
* 允许的文件后缀数组
*/
extension?: any[];
/**
* original 原图,compressed 压缩图,默认二者都有
*/
sizeType?: string | string[];
/**
* album 从相册选图,camera 使用相机,默认二者都有
*/
sourceType?: string | string[];
/**
* 摄像切换
* - front: 前置摄像头
* - back: 后置摄像头
*/
camera?: 'front' | 'back';
/**
* 是否压缩所选的视频源文件,默认值为true,需要压缩
*/
compressed?: boolean;
/**
* 拍摄视频最长拍摄时间,单位秒。最长支持 60 秒
*/
maxDuration?: number;
/**
* 选择文件后的回调
*/
onChooseFile?: (result: ChooseAndUploadFileOnChooseFileCallbackResult) => void;
/**
* 上传进度回调
*/
onUploadProgress?: (result: ChooseAndUploadFileOnUploadProgressCallbackResult) => void;
/**
* 接口调用成功的回调函数
*/
success?: (result: ChooseAndUploadFileSuccessCallbackResult) => void;
/**
* 接口调用失败的回调函数
*/
fail?: (result: any) => void;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (result: any) => void;
}
interface GetFileInfoOptions {
fileList: Array<string>;
}
interface GetFileInfoResponseFileItem {
/**
* 文件ID
*/
fileId: string;
/**
* 文件上传时间(秒)
*/
gmtCreate: number;
/**
* 文件最近更改时间(秒)
*/
gmtModified: number;
/**
* 文件原始名称
*/
name: string;
/**
* 文件大小(Byte)
*/
size: number;
/**
* 文件类型
*/
type: string;
/**
* 文件CDN加速访问下载链接
*/
url: string;
}
interface GetFileInfoResponse {
fileList: Array<GetFileInfoResponseFileItem>;
}
interface UniCloud {
/**
* 上传文件到云端
*
* 文档: [https://uniapp.dcloud.io/uniCloud/storage?id=uploadfile](https://uniapp.dcloud.io/uniCloud/storage?id=uploadfile)
*/
uploadFile(options: UploadFileOptions): Promise<any>;
/**
* 选择并上传文件
*
* 文档: [https://uniapp.dcloud.io/uniCloud/storage?id=chooseanduploadfile](https://uniapp.dcloud.io/uniCloud/storage?id=chooseanduploadfile)
*/
chooseAndUploadFile(options: ChooseAndUploadFileOptions): Promise<any>;
/**
* 删除云端文件
*
* 文档: [https://uniapp.dcloud.io/uniCloud/storage?id=deletefile](https://uniapp.dcloud.io/uniCloud/storage?id=deletefile)
*/
deleteFile(options: DeleteFileOptions): Promise<any>;
/**
* 获取文件临时链接
*
* 文档: [https://uniapp.dcloud.io/uniCloud/storage?id=gettempfileurl](https://uniapp.dcloud.io/uniCloud/storage?id=gettempfileurl)
*/
getTempFileURL(options: GetTempFileURLOptions): Promise<any>;
/**
* 获取文件信息,阿里云专用
*
* 文档: [https://uniapp.dcloud.io/uniCloud/storage?id=get-file-info](https://uniapp.dcloud.io/uniCloud/storage?id=get-file-info)
*/
getFileInfo(options: GetFileInfoOptions): Promise<GetFileInfoResponse>;
}
}
@@ -0,0 +1,21 @@
declare namespace UniCloudNamespace {
interface ConnectWebSocketOptions {
/**
* WebSocket云函数/云对象名称
*/
name: string | string.CloudFunctionString;
/**
* 建立连接时需要传递的参数, 仅在 connection 事件中接收到
*/
query?: Record<string, string>;
}
interface UniCloud {
/**
* 快速连接 WebSocket 服务
*
* 文档: [uniCloud.connectWebSocket](https://doc.dcloud.net.cn/uniCloud/websocket.html#unicloud-connectwebsocket)
*/
connectWebSocket(options: ConnectWebSocketOptions): UniApp.SocketTask;
}
}
@@ -0,0 +1,2 @@
/// <reference path="./base.d.ts" />
/// <reference path="./extension/index.d.ts" />
@@ -0,0 +1,2 @@
/// <reference path="./wx/index.d.ts" />
/// <reference path="./promisify/index.d.ts" />
@@ -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]>>;
}
@@ -0,0 +1,2 @@
/// <reference path="./common.d.ts" />
/// <reference path="./uni.d.ts" />
@@ -0,0 +1,140 @@
interface Uni {
startFacialRecognitionVerify<T extends UniNamespace.StartFacialRecognitionVerifyOption = UniNamespace.StartFacialRecognitionVerifyOption>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.StartFacialRecognitionVerifyOption>;
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>;
getImageInfo<T extends UniNamespace.GetImageInfoOptions = UniNamespace.GetImageInfoOptions>(options: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.GetImageInfoOptions>;
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 = any, U extends UniNamespace.GetStorageOptions<T> = UniNamespace.GetStorageOptions<T>>(options: U): UniNamespace.PromisifySuccessResult<U, UniNamespace.GetStorageOptions<T>>;
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>;
getSystemInfo<T extends UniNamespace.GetSystemInfoOptions = UniNamespace.GetSystemInfoOptions>(options?: T): UniNamespace.PromisifySuccessResult<T, UniNamespace.GetSystemInfoOptions>;
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
+68
View File
@@ -0,0 +1,68 @@
declare namespace UniNamespace {
interface GeneralCallbackResult {
/**
* 错误信息
*/
errMsg: string;
}
/**
* 小程序错误事件的监听函数
*/
type OnAppErrorCallback = (
/** 错误信息,包含堆栈 */
error: string
) => void;
/**
* onError 传入的监听函数。不传此参数则移除所有监听函数。
*/
type OffAppErrorCallback = (res: GeneralCallbackResult) => void;
interface SourceError {
subject?: string;
code?: number;
message?: string;
cause?: SourceError | AggregateError;
}
// 聚合源错误信息
interface AggregateError extends SourceError {
errors: Array<SourceError | AggregateError>;
}
interface UniError {
errSubject: string;
errCode: number;
errMsg: string;
data?: object;
cause?: SourceError | AggregateError;
}
}
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;
}
@@ -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;
}
}
@@ -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;
}
@@ -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;
}
+14
View File
@@ -0,0 +1,14 @@
export interface AsyncOptions {
/**
* 接口调用成功的回调函数
*/
success?: (result: any) => void;
/**
* 接口调用失败的回调函数
*/
fail?: (result: any) => void;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (result: any) => void;
}
@@ -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" />
+200
View File
@@ -0,0 +1,200 @@
declare namespace UniNamespace {
interface RequestOptions {
/**
* 资源url
*/
url: string;
/**
* 请求的参数
*/
data?: string | AnyObject | ArrayBuffer;
/**
* 设置请求的 header,header 中不能设置 Referer。
*/
header?: any;
/**
* 默认为 GET
* 可以是:OPTIONS,GET,HEAD,POST,PUT,DELETE,TRACE,CONNECT
*/
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?: string;
/**
* 开启 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 {
/**
* 中断请求任务
* @tutorial https://uniapp.dcloud.net.cn/api/request/request.html#request
* @uniPlatform {
* "app": {
* "android": {
* "osVer": "4.4",
* "uniVer": "√",
* "unixVer": "3.9.0"
* },
* "ios": {
* "osVer": "9.0",
* "uniVer": "√",
* "unixVer": "3.9.0"
* }
* }
* }
* @example ```typescript
* var requestTask = uni.request({
* url: 'http://192.168.12.106:8080/postHalo', //仅为示例,并非真实接口地址。
* complete: ()=> {}
* });
* requestTask.abort();
* ```
*/
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)
* @tutorial https://uniapp.dcloud.net.cn/api/request/request.html
* @uniPlatform {
* "app": {
* "android": {
* "osVer": "4.4",
* "uniVer": "√",
* "unixVer": "3.9.0"
* },
* "ios": {
* "osVer": "9.0",
* "uniVer": "√",
* "unixVer": "3.9.0"
* }
* }
* }
* @example ```typescript
* uni.request({
* url: "http://192.168.12.106:8080/postHalo",
* dataType: "json",
* responseType: "json",
* method: "POST",
* data: {
* platform: "ios",
* },
* // header: {
* // "Content-Type": "application/json",
* // },
* timeout: 6000,
* sslVerify: false,
* withCredentials: false,
* firstIpv4: false,
* success(res) {
* console.log("success :", res.data);
* },
* fail(e) {
* console.log(e);
* },
* complete(res) {
* console.log("complete :", res);
* },
* });
* ```
*/
request(options: UniNamespace.RequestOptions): UniNamespace.RequestTask;
}
@@ -0,0 +1,26 @@
declare namespace UniNamespace {
// 监听消息Callback
type WorkerOnMessageCallback = (message: any) => void;
// Worker错误callback
type WorkerOnErrorCallback = (error: any) => void;
interface WorkerOptions {
/**
* 可转移对象数组,默认值为空数组
* 仅鸿蒙、web平台支持,参考:https://developer.mozilla.org/zh-CN/docs/Web/API/Web_Workers_API/Transferable_objects
*/
transfer?: any[];
}
// Worker对象
interface Worker {
onMessage(listener: WorkerOnMessageCallback): void;
onError(listener: WorkerOnErrorCallback): void;
postMessage(message: any, options?: WorkerOptions): void;
terminate(): void;
}
}
interface Uni {
createWorker(url: string): UniNamespace.Worker;
}
@@ -0,0 +1,61 @@
declare namespace UniNamespace {
interface StartFacialRecognitionVerifyCallbackResult {
/**
* 错误码,成功时为0
*/
errCode: number;
/**
* 错误信息
*/
errMsg: string;
/**
* 抛出错误的模块/主题名
*/
errSubject?: string;
/**
* 引起此错误的下层错误
*/
cause?: any;
}
interface StartFacialRecognitionVerifyOption {
/**
* 认证流水号,由服务端根据接入的业务模式调用对应的初始化接口获取
*/
certifyId: string;
/**
* 刷脸圈的颜色
*/
progressBarColor?: string;
/**
* 认证界面UI朝向。port 为竖屏,land 为横屏,默认为 port
*/
screenOrientation?: string;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (result: StartFacialRecognitionVerifyCallbackResult) => void;
/**
* 接口调用失败的回调函数
*/
fail?: (result: StartFacialRecognitionVerifyCallbackResult) => void;
/**
* 接口调用成功的回调函数
*/
success?: (result: StartFacialRecognitionVerifyCallbackResult) => void;
}
}
interface Uni {
/**
* 获取设备信息MetaInfo
*
* 文档: [https://uniapp.dcloud.net.cn/uniCloud/frv/dev.html#get-meta-info](https://uniapp.dcloud.net.cn/uniCloud/frv/dev.html#get-meta-info)
*/
getFacialRecognitionMetaInfo(): string;
/**
* 调起实人认证界面
*
* 文档: [https://uniapp.dcloud.net.cn/uniCloud/frv/dev.html#start-frv](https://uniapp.dcloud.net.cn/uniCloud/frv/dev.html#start-frv)
*/
startFacialRecognitionVerify(options: UniNamespace.StartFacialRecognitionVerifyOption): void;
}
@@ -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;
}
@@ -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;
}
+386
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;
}
@@ -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;
}
+6
View File
@@ -0,0 +1,6 @@
/// <reference path="./getBatteryInfo.d.ts" />
/// <reference path="./MemoryWarning.d.ts" />
/// <reference path="./UserCaptureScreen.d.ts" />
/// <reference path="./Wifi.d.ts" />
/// <reference path="./FacialRecognition.d.ts" />
/// <reference path="./CreateWorker.d.ts" />
+3
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
+202
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.
+307
View File
@@ -0,0 +1,307 @@
'use strict';
var vue = require('vue');
var shared = require('@vue/shared');
var uniShared = require('@dcloudio/uni-shared');
function assertKey(key, shallow = false) {
if (!key) {
throw new Error(`${shallow ? 'shallowSsrRef' : 'ssrRef'}: You must provide a key.`);
}
}
function proxy(target, track, trigger) {
return new Proxy(target, {
get(target, prop) {
track();
if (shared.isObject(target[prop])) {
return proxy(target[prop], track, trigger);
}
return Reflect.get(target, prop);
},
set(obj, prop, newVal) {
const result = Reflect.set(obj, prop, newVal);
trigger();
return result;
},
});
}
const globalData = {};
const ssrServerRef = (value, key, shallow = false) => {
assertKey(key, shallow);
const ctx = vue.getCurrentInstance() && vue.useSSRContext();
let state;
if (ctx) {
const __uniSSR = ctx[uniShared.UNI_SSR] || (ctx[uniShared.UNI_SSR] = {});
state = __uniSSR[uniShared.UNI_SSR_DATA] || (__uniSSR[uniShared.UNI_SSR_DATA] = {});
}
else {
state = globalData;
}
state[key] = uniShared.sanitise(value);
// SSR 模式下 watchEffect 不生效 https://github.com/vuejs/vue-next/blob/master/packages/runtime-core/src/apiWatch.ts#L283
// 故自定义ref
return vue.customRef((track, trigger) => {
const customTrigger = () => (trigger(), (state[key] = uniShared.sanitise(value)));
return {
get: () => {
track();
if (!shallow && shared.isObject(value)) {
return proxy(value, track, customTrigger);
}
return value;
},
set: (v) => {
value = v;
customTrigger();
},
};
});
};
const ssrRef = (value, key) => {
{
return ssrServerRef(value, key);
}
};
const shallowSsrRef = (value, key) => {
{
return ssrServerRef(value, key, true);
}
};
function getSsrGlobalData() {
return uniShared.sanitise(globalData);
}
/**
* uni 对象是跨实例的,而此处列的 API 均是需要跟当前实例关联的,比如 requireNativePlugin 获取 dom 时,依赖当前 weex 实例
*/
function getCurrentSubNVue() {
return uni.getSubNVueById(plus.webview.currentWebview().id);
}
function requireNativePlugin(name) {
return weex.requireModule(name);
}
function formatAppLog(type, filename, ...args) {
// @ts-expect-error
if (uni.__log__) {
// @ts-expect-error
uni.__log__(type, filename, ...args);
}
else {
console[type].apply(console, [...args, filename]);
}
}
function formatLog(type, filename, ...args) {
if (filename) {
args.push(filename);
}
console[type].apply(console, args);
}
function resolveEasycom(component, easycom) {
return typeof component === 'string' ? easycom : component;
}
/// <reference types="@dcloudio/types" />
function isUniApp(target) {
const proxy = target === null || target === void 0 ? void 0 : target.proxy;
const ctx = target === null || target === void 0 ? void 0 : target.ctx;
const type = target === null || target === void 0 ? void 0 : target.type;
return ((proxy === null || proxy === void 0 ? void 0 : proxy.$mpType) === 'app' || (ctx === null || ctx === void 0 ? void 0 : ctx.$mpType) === 'app' || (type === null || type === void 0 ? void 0 : type.mpType) === 'app');
}
function getAppVm() {
const app = getApp({ allowDefault: true });
return app === null || app === void 0 ? void 0 : app.$vm;
}
function removeAppHook(vm, name, hook, originalHook, target) {
const hooks = vm.$[name];
if (!Array.isArray(hooks)) {
return;
}
for (let i = hooks.length - 1; i >= 0; i--) {
const appHook = hooks[i];
if (appHook === hook ||
(originalHook &&
appHook.__uni_app_hook === originalHook &&
appHook.__uni_app_target === target)) {
hooks.splice(i, 1);
}
}
}
function isTargetInvalid(target) {
var _a;
return (target === null || target === void 0 ? void 0 : target.isUnmounted) || (target === null || target === void 0 ? void 0 : target.__isUnload) || ((_a = target === null || target === void 0 ? void 0 : target.root) === null || _a === void 0 ? void 0 : _a.__isUnload);
}
function queueRemoveAppHook(removeHook) {
Promise.resolve().then(removeHook);
}
function injectAppHook(lifecycle, hook, target) {
const isAppInstance = isUniApp(target);
const appVm = getAppVm();
const appInstance = isAppInstance ? target : appVm === null || appVm === void 0 ? void 0 : appVm.$;
if (appInstance) {
if (isAppInstance) {
vue.injectHook(lifecycle, hook, appInstance);
return;
}
let isRemoved = false;
let wrappedHook;
const removeHook = () => {
if (isRemoved || !wrappedHook) {
return;
}
isRemoved = true;
const appVm = getAppVm();
appVm && removeAppHook(appVm, lifecycle, wrappedHook, hook, target);
};
const appHook = ((...args) => {
if (isRemoved || isTargetInvalid(target)) {
queueRemoveAppHook(removeHook);
return;
}
return hook(...args);
});
wrappedHook = vue.injectHook(lifecycle, appHook, appInstance);
if (wrappedHook) {
wrappedHook.__uni_app_hook = hook;
wrappedHook.__uni_app_target = target;
if (isTargetInvalid(target)) {
removeHook();
}
}
// 如果不是App,那么需要监听当前target的销毁事件,来移除App上的钩子
if (target && wrappedHook) {
vue.onBeforeUnmount(() => removeHook(), target);
vue.injectHook(uniShared.ON_UNLOAD, () => removeHook(), target);
}
}
}
// function isUniPage(target: ComponentInternalInstance | null): boolean {
// if (target && 'renderer' in target) {
// return target.renderer === 'page'
// }
// return true
// }
const createLifeCycleHook = (lifecycle, flag = 0 /* HookFlags.UNKNOWN */) => (hook, target = vue.getCurrentInstance()) => {
if (vue.isInSSRComponentSetup)
return;
if (flag === 1 /* HookFlags.APP */) {
injectAppHook(lifecycle, hook, target);
return;
}
// post-create lifecycle registrations are noops during SSR
vue.injectHook(lifecycle, hook, target);
};
const onAppShow = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_SHOW, 1 /* HookFlags.APP */);
const onAppHide = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_HIDE, 1 /* HookFlags.APP */);
const onShow = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_SHOW, 2 /* HookFlags.PAGE */);
const onHide = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_HIDE, 2 /* HookFlags.PAGE */);
const onLaunch = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_LAUNCH, 1 /* HookFlags.APP */);
const onError = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_ERROR, 1 /* HookFlags.APP */);
const onThemeChange = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_THEME_CHANGE, 1 /* HookFlags.APP */);
const onPageNotFound = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_PAGE_NOT_FOUND, 1 /* HookFlags.APP */);
const onUnhandledRejection = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_UNHANDLE_REJECTION, 1 /* HookFlags.APP */);
const onLastPageBackPress = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_LAST_PAGE_BACK_PRESS, 1 /* HookFlags.APP */);
const onExit = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_EXIT, 1 /* HookFlags.APP */);
const onInit = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_INIT, 2 /* HookFlags.PAGE */ | 4 /* HookFlags.COMPONENT */);
// 小程序如果想在 setup 的 props 传递页面参数,需要定义 props,故同时暴露 onLoad 吧
const onLoad = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_LOAD, 2 /* HookFlags.PAGE */);
const onReady = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_READY, 2 /* HookFlags.PAGE */);
const onUnload = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_UNLOAD, 2 /* HookFlags.PAGE */);
const onResize = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_RESIZE, 2 /* HookFlags.PAGE */);
const onBackPress = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_BACK_PRESS, 2 /* HookFlags.PAGE */);
const onPageScroll = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_PAGE_SCROLL, 2 /* HookFlags.PAGE */);
const onTabItemTap = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_TAB_ITEM_TAP, 2 /* HookFlags.PAGE */);
const onReachBottom = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_REACH_BOTTOM, 2 /* HookFlags.PAGE */);
const onPullDownRefresh = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_PULL_DOWN_REFRESH, 2 /* HookFlags.PAGE */);
const onSaveExitState =
/*#__PURE__*/ createLifeCycleHook(uniShared.ON_SAVE_EXIT_STATE, 2 /* HookFlags.PAGE */);
const onTitleClick = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_TITLE_CLICK, 2 /* HookFlags.PAGE */);
const onShareTimeline = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_SHARE_TIMELINE, 2 /* HookFlags.PAGE */);
const onShareChat = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_SHARE_CHAT, 2 /* HookFlags.PAGE */);
const onAddToFavorites = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_ADD_TO_FAVORITES, 2 /* HookFlags.PAGE */);
const onShareAppMessage = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_SHARE_APP_MESSAGE, 2 /* HookFlags.PAGE */);
const onCopyUrl = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_COPY_URL, 2 /* HookFlags.PAGE */);
const onUploadDouyinVideo = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_UPLOAD_DOUYIN_VIDEO, 2 /* HookFlags.PAGE */);
const onLiveMount = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_LIVE_MOUNT, 2 /* HookFlags.PAGE */);
const onNavigationBarButtonTap = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_NAVIGATION_BAR_BUTTON_TAP, 2 /* HookFlags.PAGE */);
const onNavigationBarSearchInputChanged =
/*#__PURE__*/ createLifeCycleHook(uniShared.ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED, 2 /* HookFlags.PAGE */);
const onNavigationBarSearchInputClicked =
/*#__PURE__*/ createLifeCycleHook(uniShared.ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED, 2 /* HookFlags.PAGE */);
const onNavigationBarSearchInputConfirmed =
/*#__PURE__*/ createLifeCycleHook(uniShared.ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED, 2 /* HookFlags.PAGE */);
const onNavigationBarSearchInputFocusChanged =
/*#__PURE__*/ createLifeCycleHook(uniShared.ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED, 2 /* HookFlags.PAGE */);
const onPageShow = onShow;
const onPageHide = onHide;
function renderComponentSlot(slots, name, props = null) {
if (slots[name]) {
return slots[name](props);
}
return null;
}
Object.defineProperty(exports, "capitalize", {
enumerable: true,
get: function () { return shared.capitalize; }
});
Object.defineProperty(exports, "extend", {
enumerable: true,
get: function () { return shared.extend; }
});
Object.defineProperty(exports, "hasOwn", {
enumerable: true,
get: function () { return shared.hasOwn; }
});
Object.defineProperty(exports, "isPlainObject", {
enumerable: true,
get: function () { return shared.isPlainObject; }
});
exports.formatAppLog = formatAppLog;
exports.formatLog = formatLog;
exports.getCurrentSubNVue = getCurrentSubNVue;
exports.getSsrGlobalData = getSsrGlobalData;
exports.onAddToFavorites = onAddToFavorites;
exports.onAppHide = onAppHide;
exports.onAppShow = onAppShow;
exports.onBackPress = onBackPress;
exports.onCopyUrl = onCopyUrl;
exports.onError = onError;
exports.onExit = onExit;
exports.onHide = onHide;
exports.onInit = onInit;
exports.onLastPageBackPress = onLastPageBackPress;
exports.onLaunch = onLaunch;
exports.onLiveMount = onLiveMount;
exports.onLoad = onLoad;
exports.onNavigationBarButtonTap = onNavigationBarButtonTap;
exports.onNavigationBarSearchInputChanged = onNavigationBarSearchInputChanged;
exports.onNavigationBarSearchInputClicked = onNavigationBarSearchInputClicked;
exports.onNavigationBarSearchInputConfirmed = onNavigationBarSearchInputConfirmed;
exports.onNavigationBarSearchInputFocusChanged = onNavigationBarSearchInputFocusChanged;
exports.onPageHide = onPageHide;
exports.onPageNotFound = onPageNotFound;
exports.onPageScroll = onPageScroll;
exports.onPageShow = onPageShow;
exports.onPullDownRefresh = onPullDownRefresh;
exports.onReachBottom = onReachBottom;
exports.onReady = onReady;
exports.onResize = onResize;
exports.onSaveExitState = onSaveExitState;
exports.onShareAppMessage = onShareAppMessage;
exports.onShareChat = onShareChat;
exports.onShareTimeline = onShareTimeline;
exports.onShow = onShow;
exports.onTabItemTap = onTabItemTap;
exports.onThemeChange = onThemeChange;
exports.onTitleClick = onTitleClick;
exports.onUnhandledRejection = onUnhandledRejection;
exports.onUnload = onUnload;
exports.onUploadDouyinVideo = onUploadDouyinVideo;
exports.renderComponentSlot = renderComponentSlot;
exports.requireNativePlugin = requireNativePlugin;
exports.resolveEasycom = resolveEasycom;
exports.shallowSsrRef = shallowSsrRef;
exports.ssrRef = ssrRef;
+217
View File
@@ -0,0 +1,217 @@
import { shallowRef, ref, getCurrentInstance, isInSSRComponentSetup, injectHook, onBeforeUnmount } from 'vue';
import { hasOwn } from '@vue/shared';
export { capitalize, extend, hasOwn, isPlainObject } from '@vue/shared';
import { sanitise, UNI_SSR_DATA, UNI_SSR_GLOBAL_DATA, UNI_SSR, ON_SHOW, ON_HIDE, ON_LAUNCH, ON_ERROR, ON_THEME_CHANGE, ON_PAGE_NOT_FOUND, ON_UNHANDLE_REJECTION, ON_LAST_PAGE_BACK_PRESS, ON_EXIT, ON_INIT, ON_LOAD, ON_READY, ON_UNLOAD, ON_RESIZE, ON_BACK_PRESS, ON_PAGE_SCROLL, ON_TAB_ITEM_TAP, ON_REACH_BOTTOM, ON_PULL_DOWN_REFRESH, ON_SAVE_EXIT_STATE, ON_TITLE_CLICK, ON_SHARE_TIMELINE, ON_SHARE_CHAT, ON_ADD_TO_FAVORITES, ON_SHARE_APP_MESSAGE, ON_COPY_URL, ON_UPLOAD_DOUYIN_VIDEO, ON_LIVE_MOUNT, ON_NAVIGATION_BAR_BUTTON_TAP, ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED, ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED, ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED, ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED } from '@dcloudio/uni-shared';
function getSSRDataType() {
return getCurrentInstance() ? UNI_SSR_DATA : UNI_SSR_GLOBAL_DATA;
}
function assertKey(key, shallow = false) {
if (!key) {
throw new Error(`${shallow ? 'shallowSsrRef' : 'ssrRef'}: You must provide a key.`);
}
}
const ssrClientRef = (value, key, shallow = false) => {
const valRef = shallow ? shallowRef(value) : ref(value);
// 非 h5 平台
if (typeof window === 'undefined') {
return valRef;
}
const __uniSSR = window[UNI_SSR];
if (!__uniSSR) {
return valRef;
}
const type = getSSRDataType();
assertKey(key, shallow);
if (hasOwn(__uniSSR[type], key)) {
valRef.value = __uniSSR[type][key];
if (type === UNI_SSR_DATA) {
delete __uniSSR[type][key]; // TODO 非全局数据仅使用一次?否则下次还会再次使用该数据
}
}
return valRef;
};
const globalData = {};
const ssrRef = (value, key) => {
return ssrClientRef(value, key);
};
const shallowSsrRef = (value, key) => {
return ssrClientRef(value, key, true);
};
function getSsrGlobalData() {
return sanitise(globalData);
}
/**
* uni 对象是跨实例的,而此处列的 API 均是需要跟当前实例关联的,比如 requireNativePlugin 获取 dom 时,依赖当前 weex 实例
*/
function getCurrentSubNVue() {
return uni.getSubNVueById(plus.webview.currentWebview().id);
}
function requireNativePlugin(name) {
return weex.requireModule(name);
}
function formatAppLog(type, filename, ...args) {
// @ts-expect-error
if (uni.__log__) {
// @ts-expect-error
uni.__log__(type, filename, ...args);
}
else {
console[type].apply(console, [...args, filename]);
}
}
function formatLog(type, filename, ...args) {
if (filename) {
args.push(filename);
}
console[type].apply(console, args);
}
function resolveEasycom(component, easycom) {
return typeof component === 'string' ? easycom : component;
}
/// <reference types="@dcloudio/types" />
function isUniApp(target) {
const proxy = target === null || target === void 0 ? void 0 : target.proxy;
const ctx = target === null || target === void 0 ? void 0 : target.ctx;
const type = target === null || target === void 0 ? void 0 : target.type;
return ((proxy === null || proxy === void 0 ? void 0 : proxy.$mpType) === 'app' || (ctx === null || ctx === void 0 ? void 0 : ctx.$mpType) === 'app' || (type === null || type === void 0 ? void 0 : type.mpType) === 'app');
}
function getAppVm() {
const app = getApp({ allowDefault: true });
return app === null || app === void 0 ? void 0 : app.$vm;
}
function removeAppHook(vm, name, hook, originalHook, target) {
const hooks = vm.$[name];
if (!Array.isArray(hooks)) {
return;
}
for (let i = hooks.length - 1; i >= 0; i--) {
const appHook = hooks[i];
if (appHook === hook ||
(originalHook &&
appHook.__uni_app_hook === originalHook &&
appHook.__uni_app_target === target)) {
hooks.splice(i, 1);
}
}
}
function isTargetInvalid(target) {
var _a;
return (target === null || target === void 0 ? void 0 : target.isUnmounted) || (target === null || target === void 0 ? void 0 : target.__isUnload) || ((_a = target === null || target === void 0 ? void 0 : target.root) === null || _a === void 0 ? void 0 : _a.__isUnload);
}
function queueRemoveAppHook(removeHook) {
Promise.resolve().then(removeHook);
}
function injectAppHook(lifecycle, hook, target) {
const isAppInstance = isUniApp(target);
const appVm = getAppVm();
const appInstance = isAppInstance ? target : appVm === null || appVm === void 0 ? void 0 : appVm.$;
if (appInstance) {
if (isAppInstance) {
injectHook(lifecycle, hook, appInstance);
return;
}
let isRemoved = false;
let wrappedHook;
const removeHook = () => {
if (isRemoved || !wrappedHook) {
return;
}
isRemoved = true;
const appVm = getAppVm();
appVm && removeAppHook(appVm, lifecycle, wrappedHook, hook, target);
};
const appHook = ((...args) => {
if (isRemoved || isTargetInvalid(target)) {
queueRemoveAppHook(removeHook);
return;
}
return hook(...args);
});
wrappedHook = injectHook(lifecycle, appHook, appInstance);
if (wrappedHook) {
wrappedHook.__uni_app_hook = hook;
wrappedHook.__uni_app_target = target;
if (isTargetInvalid(target)) {
removeHook();
}
}
// 如果不是App,那么需要监听当前target的销毁事件,来移除App上的钩子
if (target && wrappedHook) {
onBeforeUnmount(() => removeHook(), target);
injectHook(ON_UNLOAD, () => removeHook(), target);
}
}
}
// function isUniPage(target: ComponentInternalInstance | null): boolean {
// if (target && 'renderer' in target) {
// return target.renderer === 'page'
// }
// return true
// }
const createLifeCycleHook = (lifecycle, flag = 0 /* HookFlags.UNKNOWN */) => (hook, target = getCurrentInstance()) => {
if (isInSSRComponentSetup)
return;
if (flag === 1 /* HookFlags.APP */) {
injectAppHook(lifecycle, hook, target);
return;
}
// post-create lifecycle registrations are noops during SSR
injectHook(lifecycle, hook, target);
};
const onAppShow = /*#__PURE__*/ createLifeCycleHook(ON_SHOW, 1 /* HookFlags.APP */);
const onAppHide = /*#__PURE__*/ createLifeCycleHook(ON_HIDE, 1 /* HookFlags.APP */);
const onShow = /*#__PURE__*/ createLifeCycleHook(ON_SHOW, 2 /* HookFlags.PAGE */);
const onHide = /*#__PURE__*/ createLifeCycleHook(ON_HIDE, 2 /* HookFlags.PAGE */);
const onLaunch = /*#__PURE__*/ createLifeCycleHook(ON_LAUNCH, 1 /* HookFlags.APP */);
const onError = /*#__PURE__*/ createLifeCycleHook(ON_ERROR, 1 /* HookFlags.APP */);
const onThemeChange = /*#__PURE__*/ createLifeCycleHook(ON_THEME_CHANGE, 1 /* HookFlags.APP */);
const onPageNotFound = /*#__PURE__*/ createLifeCycleHook(ON_PAGE_NOT_FOUND, 1 /* HookFlags.APP */);
const onUnhandledRejection = /*#__PURE__*/ createLifeCycleHook(ON_UNHANDLE_REJECTION, 1 /* HookFlags.APP */);
const onLastPageBackPress = /*#__PURE__*/ createLifeCycleHook(ON_LAST_PAGE_BACK_PRESS, 1 /* HookFlags.APP */);
const onExit = /*#__PURE__*/ createLifeCycleHook(ON_EXIT, 1 /* HookFlags.APP */);
const onInit = /*#__PURE__*/ createLifeCycleHook(ON_INIT, 2 /* HookFlags.PAGE */ | 4 /* HookFlags.COMPONENT */);
// 小程序如果想在 setup 的 props 传递页面参数,需要定义 props,故同时暴露 onLoad 吧
const onLoad = /*#__PURE__*/ createLifeCycleHook(ON_LOAD, 2 /* HookFlags.PAGE */);
const onReady = /*#__PURE__*/ createLifeCycleHook(ON_READY, 2 /* HookFlags.PAGE */);
const onUnload = /*#__PURE__*/ createLifeCycleHook(ON_UNLOAD, 2 /* HookFlags.PAGE */);
const onResize = /*#__PURE__*/ createLifeCycleHook(ON_RESIZE, 2 /* HookFlags.PAGE */);
const onBackPress = /*#__PURE__*/ createLifeCycleHook(ON_BACK_PRESS, 2 /* HookFlags.PAGE */);
const onPageScroll = /*#__PURE__*/ createLifeCycleHook(ON_PAGE_SCROLL, 2 /* HookFlags.PAGE */);
const onTabItemTap = /*#__PURE__*/ createLifeCycleHook(ON_TAB_ITEM_TAP, 2 /* HookFlags.PAGE */);
const onReachBottom = /*#__PURE__*/ createLifeCycleHook(ON_REACH_BOTTOM, 2 /* HookFlags.PAGE */);
const onPullDownRefresh = /*#__PURE__*/ createLifeCycleHook(ON_PULL_DOWN_REFRESH, 2 /* HookFlags.PAGE */);
const onSaveExitState =
/*#__PURE__*/ createLifeCycleHook(ON_SAVE_EXIT_STATE, 2 /* HookFlags.PAGE */);
const onTitleClick = /*#__PURE__*/ createLifeCycleHook(ON_TITLE_CLICK, 2 /* HookFlags.PAGE */);
const onShareTimeline = /*#__PURE__*/ createLifeCycleHook(ON_SHARE_TIMELINE, 2 /* HookFlags.PAGE */);
const onShareChat = /*#__PURE__*/ createLifeCycleHook(ON_SHARE_CHAT, 2 /* HookFlags.PAGE */);
const onAddToFavorites = /*#__PURE__*/ createLifeCycleHook(ON_ADD_TO_FAVORITES, 2 /* HookFlags.PAGE */);
const onShareAppMessage = /*#__PURE__*/ createLifeCycleHook(ON_SHARE_APP_MESSAGE, 2 /* HookFlags.PAGE */);
const onCopyUrl = /*#__PURE__*/ createLifeCycleHook(ON_COPY_URL, 2 /* HookFlags.PAGE */);
const onUploadDouyinVideo = /*#__PURE__*/ createLifeCycleHook(ON_UPLOAD_DOUYIN_VIDEO, 2 /* HookFlags.PAGE */);
const onLiveMount = /*#__PURE__*/ createLifeCycleHook(ON_LIVE_MOUNT, 2 /* HookFlags.PAGE */);
const onNavigationBarButtonTap = /*#__PURE__*/ createLifeCycleHook(ON_NAVIGATION_BAR_BUTTON_TAP, 2 /* HookFlags.PAGE */);
const onNavigationBarSearchInputChanged =
/*#__PURE__*/ createLifeCycleHook(ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED, 2 /* HookFlags.PAGE */);
const onNavigationBarSearchInputClicked =
/*#__PURE__*/ createLifeCycleHook(ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED, 2 /* HookFlags.PAGE */);
const onNavigationBarSearchInputConfirmed =
/*#__PURE__*/ createLifeCycleHook(ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED, 2 /* HookFlags.PAGE */);
const onNavigationBarSearchInputFocusChanged =
/*#__PURE__*/ createLifeCycleHook(ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED, 2 /* HookFlags.PAGE */);
const onPageShow = onShow;
const onPageHide = onHide;
function renderComponentSlot(slots, name, props = null) {
if (slots[name]) {
return slots[name](props);
}
return null;
}
export { formatAppLog, formatLog, getCurrentSubNVue, getSsrGlobalData, onAddToFavorites, onAppHide, onAppShow, onBackPress, onCopyUrl, onError, onExit, onHide, onInit, onLastPageBackPress, onLaunch, onLiveMount, onLoad, onNavigationBarButtonTap, onNavigationBarSearchInputChanged, onNavigationBarSearchInputClicked, onNavigationBarSearchInputConfirmed, onNavigationBarSearchInputFocusChanged, onPageHide, onPageNotFound, onPageScroll, onPageShow, onPullDownRefresh, onReachBottom, onReady, onResize, onSaveExitState, onShareAppMessage, onShareChat, onShareTimeline, onShow, onTabItemTap, onThemeChange, onTitleClick, onUnhandledRejection, onUnload, onUploadDouyinVideo, renderComponentSlot, requireNativePlugin, resolveEasycom, shallowSsrRef, ssrRef };
+733
View File
@@ -0,0 +1,733 @@
function arrayPop(array) {
if (array.length === 0) {
return null;
}
return array.pop();
}
function arrayShift(array) {
if (array.length === 0) {
return null;
}
return array.shift();
}
function arrayFind(array, predicate) {
const index = array.findIndex(predicate);
if (index < 0) {
return null;
}
return array[index];
}
function arrayFindLast(array, predicate) {
const index = array.findLastIndex(predicate);
if (index < 0) {
return null;
}
return array[index];
}
function arrayAt(array, index) {
if (index < -array.length || index >= array.length) {
return null;
}
return array.at(index);
}
/**
* copy from @uts/shared
*/
const UTS_CLASS_METADATA_KIND_LIST = [0, 1, 2];
function getType(val) {
return Object.prototype.toString.call(val).slice(8, -1).toLowerCase();
}
function isPlainObject(val) {
if (val == null || typeof val !== 'object') {
return false;
}
const proto = Object.getPrototypeOf(val);
return proto === Object.prototype || proto === null;
}
// TODO 实现UTSError
class UTSError extends Error {
constructor(message) {
super(message);
}
}
function isUTSMetadata(metadata) {
return !!(metadata &&
UTS_CLASS_METADATA_KIND_LIST.includes(metadata.kind) &&
metadata.interfaces);
}
function isNativeType(proto) {
return !proto || proto === Object.prototype;
}
const utsMetadataKey = "$UTSMetadata$" /* IDENTIFIER.UTS_METADATA */;
/**
* 处理复杂的继承关系。
* 例如:
* class A extends abstract class B,abstract class B implements interface C
* new A() instanceof C -> true
*/
function getParentTypeList(type) {
const metadata = utsMetadataKey in type ? type[utsMetadataKey] : {};
let interfaces = [];
if (!isUTSMetadata(metadata)) {
interfaces = [];
}
else {
interfaces = metadata.interfaces || [];
}
const proto = Object.getPrototypeOf(type);
if (!isNativeType(proto)) {
interfaces.push(proto.constructor);
}
return interfaces;
}
function isImplementationOf(leftType, rightType, visited = []) {
if (isNativeType(leftType)) {
return false;
}
if (leftType === rightType) {
return true;
}
visited.push(leftType);
const parentTypeList = getParentTypeList(leftType);
return parentTypeList.some((parentType) => {
if (visited.includes(parentType)) {
return false;
}
return isImplementationOf(parentType, rightType, visited);
});
}
function isInstanceOf(value, type) {
if (type === UTSValueIterable) {
return value && value[Symbol.iterator];
}
const isNativeInstanceofType = value instanceof type;
if (isNativeInstanceofType || typeof value !== 'object' || value === null) {
return isNativeInstanceofType;
}
const proto = Object.getPrototypeOf(value).constructor;
return isImplementationOf(proto, type);
}
function isBaseType(type) {
return type === Number || type === String || type === Boolean;
}
function isUnknownType(type) {
return type === 'Unknown';
}
function isAnyType(type) {
return type === 'Any';
}
function isUTSType(type) {
return type && type.prototype && type.prototype instanceof UTSType;
}
function normalizeGenericValue(value, genericType, isJSONParse = false) {
return value == null
? null
: isBaseType(genericType) ||
isUnknownType(genericType) ||
isAnyType(genericType)
? value
: genericType === Array
? new Array(...value)
: new genericType(value, undefined, isJSONParse);
}
class UTSType {
static get$UTSMetadata$(...args) {
return {
name: '',
kind: 2 /* UTS_CLASS_METADATA_KIND.TYPE */,
interfaces: [],
fields: {},
};
}
get $UTSMetadata$() {
return UTSType.get$UTSMetadata$();
}
// TODO 缓存withGenerics结果
static withGenerics(parent, generics, isJSONParse = false) {
// 仅JSON.parse uni.request内报错,其他地方不报错
// generic类型为UTSType子类或Array或基础类型,否则报错
if (isJSONParse) {
const illegalGeneric = generics.find((item) => !(item === Array ||
isBaseType(item) ||
isUnknownType(item) ||
isAnyType(item) ||
item === UTSJSONObject ||
(item.prototype && item.prototype instanceof UTSType)));
if (illegalGeneric) {
throw new Error('Generic is not UTSType or Array or UTSJSONObject or base type, generic: ' +
illegalGeneric);
}
}
if (parent === Array) {
// 不带泛型的Array有一部分不会进入这里,需要在构造type时处理
return class UTSArray extends UTSType {
constructor(options, isJSONParse = false) {
if (!Array.isArray(options)) {
throw new UTSError(`Failed to contruct type, ${options} is not an array`);
}
super();
// @ts-expect-error
return options.map((item) => {
return normalizeGenericValue(item, generics[0], isJSONParse);
});
}
};
}
else if (parent === Map || parent === WeakMap) {
return class UTSMap extends UTSType {
constructor(options, isJSONParse = false) {
if (options == null || typeof options !== 'object') {
throw new UTSError(`Failed to contruct type, ${options} is not an object`);
}
super();
const obj = new parent();
for (const key in options) {
obj.set(normalizeGenericValue(key, generics[0], isJSONParse), normalizeGenericValue(options[key], generics[1], isJSONParse));
}
return obj;
}
};
}
else if (isUTSType(parent)) {
return class VirtualClassWithGenerics extends parent {
static get$UTSMetadata$() {
return parent.get$UTSMetadata$(...generics);
}
constructor(options, metadata = VirtualClassWithGenerics.get$UTSMetadata$(), isJSONParse = false) {
// @ts-expect-error
super(options, metadata, isJSONParse);
}
};
}
else {
return parent;
}
}
constructor() { }
static initProps(options, metadata, isJSONParse = false) {
// 为了性能,非JSON.parse场景直接返回
if (!isJSONParse) {
return options;
}
const obj = {};
if (!metadata.fields) {
return obj;
}
for (const key in metadata.fields) {
const { type, optional, jsonField } = metadata.fields[key];
const realKey = isJSONParse ? jsonField || key : key;
if (options[realKey] == null) {
if (optional) {
obj[key] = null;
continue;
}
else {
throw new UTSError(`Failed to contruct type, missing required property: ${key}`);
}
}
if (isUTSType(type)) {
// 带有泛型的数组会走此分支
obj[key] = isJSONParse
? // @ts-expect-error
new type(options[realKey], undefined, isJSONParse)
: options[realKey];
}
else if (type === Array) {
// 不带泛型的数组会走此分支
if (!Array.isArray(options[realKey])) {
throw new UTSError(`Failed to contruct type, property ${key} is not an array`);
}
obj[key] = options[realKey];
}
else {
obj[key] = options[realKey];
}
}
return obj;
}
}
function initUTSJSONObjectProperties(obj) {
const propertyList = [
'_resolveKeyPath',
'_getValue',
'toJSON',
'get',
'set',
'getAny',
'getString',
'getNumber',
'getBoolean',
'getJSON',
'getArray',
'toMap',
'forEach',
];
const propertyDescriptorMap = {};
for (let i = 0; i < propertyList.length; i++) {
const property = propertyList[i];
propertyDescriptorMap[property] = {
enumerable: false,
value: obj[property],
};
}
Object.defineProperties(obj, propertyDescriptorMap);
}
function getRealDefaultValue(defaultValue) {
return defaultValue === void 0 ? null : defaultValue;
}
class UTSJSONObject {
static keys(obj) {
return Object.keys(obj);
}
static assign(target, ...sources) {
for (let i = 0; i < sources.length; i++) {
const source = sources[i];
for (let key in source) {
target[key] = source[key];
}
}
return target;
}
constructor(content = {}) {
if (content instanceof Map) {
content.forEach((value, key) => {
this[key] = value;
});
}
else {
for (const key in content) {
if (Object.prototype.hasOwnProperty.call(content, key)) {
this[key] = content[key];
}
}
}
initUTSJSONObjectProperties(this);
}
_resolveKeyPath(keyPath) {
// 非法keyPath不抛出错误,直接返回空数组
let token = '';
const keyPathArr = [];
let inOpenParentheses = false;
for (let i = 0; i < keyPath.length; i++) {
const word = keyPath[i];
switch (word) {
case '.':
if (token.length > 0) {
keyPathArr.push(token);
token = '';
}
break;
case '[': {
inOpenParentheses = true;
if (token.length > 0) {
keyPathArr.push(token);
token = '';
}
break;
}
case ']':
if (inOpenParentheses) {
if (token.length > 0) {
const tokenFirstChar = token[0];
const tokenLastChar = token[token.length - 1];
if ((tokenFirstChar === '"' && tokenLastChar === '"') ||
(tokenFirstChar === "'" && tokenLastChar === "'") ||
(tokenFirstChar === '`' && tokenLastChar === '`')) {
if (token.length > 2) {
token = token.slice(1, -1);
}
else {
return [];
}
}
else if (!/^\d+$/.test(token)) {
return [];
}
keyPathArr.push(token);
token = '';
}
else {
return [];
}
inOpenParentheses = false;
}
else {
return [];
}
break;
default:
token += word;
break;
}
if (i === keyPath.length - 1) {
if (token.length > 0) {
keyPathArr.push(token);
token = '';
}
}
}
return keyPathArr;
}
_getValue(keyPath, defaultValue) {
const keyPathArr = this._resolveKeyPath(keyPath);
const realDefaultValue = getRealDefaultValue(defaultValue);
if (keyPathArr.length === 0) {
return realDefaultValue;
}
let value = this;
for (let i = 0; i < keyPathArr.length; i++) {
const key = keyPathArr[i];
if (value instanceof Object) {
if (key in value) {
value = value[key];
}
else {
return realDefaultValue;
}
}
else {
return realDefaultValue;
}
}
return value;
}
get(key) {
return this._getValue(key);
}
set(key, value) {
this[key] = value;
}
getAny(key, defaultValue) {
const realDefaultValue = getRealDefaultValue(defaultValue);
return this._getValue(key, realDefaultValue);
}
getString(key, defaultValue) {
const realDefaultValue = getRealDefaultValue(defaultValue);
const value = this._getValue(key, realDefaultValue);
if (typeof value === 'string') {
return value;
}
else {
return realDefaultValue;
}
}
getNumber(key, defaultValue) {
const realDefaultValue = getRealDefaultValue(defaultValue);
const value = this._getValue(key, realDefaultValue);
if (typeof value === 'number') {
return value;
}
else {
return realDefaultValue;
}
}
getBoolean(key, defaultValue) {
const realDefaultValue = getRealDefaultValue(defaultValue);
const boolean = this._getValue(key, realDefaultValue);
if (typeof boolean === 'boolean') {
return boolean;
}
else {
return realDefaultValue;
}
}
getJSON(key, defaultValue) {
const realDefaultValue = getRealDefaultValue(defaultValue);
let value = this._getValue(key, realDefaultValue);
if (value instanceof Object) {
return value;
}
else {
return realDefaultValue;
}
}
getArray(key, defaultValue) {
const realDefaultValue = getRealDefaultValue(defaultValue);
let value = this._getValue(key, realDefaultValue);
if (value instanceof Array) {
return value;
}
else {
return realDefaultValue;
}
}
toMap() {
let map = new Map();
for (let key in this) {
map.set(key, this[key]);
}
return map;
}
forEach(callback) {
for (let key in this) {
callback(this[key], key);
}
}
}
const OriginalJSON = JSON;
function createUTSJSONObjectOrArray(obj) {
if (Array.isArray(obj)) {
return obj.map((item) => {
return createUTSJSONObjectOrArray(item);
});
}
else if (isPlainObject(obj)) {
const result = new UTSJSONObject({});
for (const key in obj) {
const value = obj[key];
result[key] = createUTSJSONObjectOrArray(value);
}
return result;
}
return obj;
}
function parseObjectOrArray(object, utsType) {
const objectType = getType(object);
if (object === null || (objectType !== 'object' && objectType !== 'array')) {
return object;
}
if (utsType && utsType !== UTSJSONObject) {
try {
return new utsType(object, undefined, true);
}
catch (error) {
console.error(error);
return null;
}
}
if (objectType === 'array' || objectType === 'object') {
return createUTSJSONObjectOrArray(object);
}
return object;
}
const UTSJSON = {
parse: (text, reviver, utsType) => {
// @ts-expect-error
if (reviver && (isUTSType(reviver) || reviver === UTSJSONObject)) {
utsType = reviver;
reviver = undefined;
}
try {
const parseResult = OriginalJSON.parse(text, reviver);
return parseObjectOrArray(parseResult, utsType);
}
catch (error) {
console.error(error);
return null;
}
},
parseArray(text, utsType) {
try {
const parseResult = OriginalJSON.parse(text);
if (Array.isArray(parseResult)) {
return parseObjectOrArray(parseResult, utsType ? UTSType.withGenerics(Array, [utsType], true) : undefined);
}
return null;
}
catch (error) {
console.error(error);
return null;
}
},
parseObject(text, utsType) {
try {
const parseResult = OriginalJSON.parse(text);
if (Array.isArray(parseResult)) {
return null;
}
return parseObjectOrArray(parseResult, utsType);
}
catch (error) {
console.error(error);
return null;
}
},
stringify: (value, replacer, space) => {
try {
if (!replacer) {
const visited = new Set();
replacer = function (_, v) {
if (typeof v === 'object') {
if (visited.has(v)) {
return null;
}
visited.add(v);
}
return v;
};
}
return OriginalJSON.stringify(value, replacer, space);
}
catch (error) {
console.error(error);
return '';
}
},
};
function mapGet(map, key) {
if (!map.has(key)) {
return null;
}
return map.get(key);
}
function stringCodePointAt(str, pos) {
if (pos < 0 || pos >= str.length) {
return null;
}
return str.codePointAt(pos);
}
function stringAt(str, pos) {
if (pos < -str.length || pos >= str.length) {
return null;
}
return str.at(pos);
}
function weakMapGet(map, key) {
if (!map.has(key)) {
return null;
}
return map.get(key);
}
const UTS = {
arrayAt,
arrayFind,
arrayFindLast,
arrayPop,
arrayShift,
isInstanceOf,
UTSType,
mapGet,
stringAt,
stringCodePointAt,
weakMapGet,
JSON: UTSJSON,
};
class UniError extends Error {
constructor(errSubject, errCode, errMsg) {
let options = {};
const argsLength = Array.from(arguments).length;
switch (argsLength) {
case 0:
errSubject = '';
errMsg = '';
errCode = 0;
break;
case 1:
errMsg = errSubject;
errSubject = '';
errCode = 0;
break;
case 2:
errMsg = errSubject;
options = errCode;
errCode = options.errCode || 0;
errSubject = options.errSubject || '';
break;
}
super(errMsg);
this.name = 'UniError';
this.errSubject = errSubject;
this.errCode = errCode;
this.errMsg = errMsg;
if (options.data) {
this.data = options.data;
}
if (options.cause) {
this.cause = options.cause;
}
}
set errMsg(msg) {
this.message = msg;
}
get errMsg() {
return this.message;
}
toString() {
return this.errMsg;
}
toJSON() {
return {
errSubject: this.errSubject,
errCode: this.errCode,
errMsg: this.errMsg,
data: this.data,
cause: this.cause && typeof this.cause.toJSON === 'function'
? this.cause.toJSON()
: this.cause,
};
}
}
class UTSValueIterable {
}
function getGlobalOnce() {
if (typeof globalThis !== 'undefined') {
return globalThis;
}
// worker
if (typeof self !== 'undefined') {
return self;
}
// browser
if (typeof window !== 'undefined') {
return window;
}
// nodejs
// if (typeof global !== 'undefined') {
// return global
// }
function g() {
return this;
}
if (typeof g() !== 'undefined') {
return g();
}
return (function () {
return new Function('return this')();
})();
}
let g = undefined;
function getGlobal() {
if (g) {
return g;
}
g = getGlobalOnce();
return g;
}
const realGlobal = getGlobal();
realGlobal.UTS = UTS;
realGlobal.UTSJSONObject = UTSJSONObject;
realGlobal.UTSValueIterable = UTSValueIterable;
realGlobal.UniError = UniError;
class WorkerTaskImpl {
constructor() {
{
worker.onMessage((e) => {
this.onMessage(e);
});
}
}
entry() { }
onMessage(message) { }
postMessage(message, options = null) {
{
worker.postMessage(message);
}
}
}
// @ts-expect-error
globalThis.WorkerTaskImpl = WorkerTaskImpl;
export { UTS, UTSJSONObject, UTSValueIterable, UniError, WorkerTaskImpl };
+745
View File
@@ -0,0 +1,745 @@
(function (exports) {
'raw js';
'use strict';
function arrayPop(array) {
if (array.length === 0) {
return null;
}
return array.pop();
}
function arrayShift(array) {
if (array.length === 0) {
return null;
}
return array.shift();
}
function arrayFind(array, predicate) {
const index = array.findIndex(predicate);
if (index < 0) {
return null;
}
return array[index];
}
function arrayFindLast(array, predicate) {
const index = array.findLastIndex(predicate);
if (index < 0) {
return null;
}
return array[index];
}
function arrayAt(array, index) {
if (index < -array.length || index >= array.length) {
return null;
}
return array.at(index);
}
/**
* copy from @uts/shared
*/
const UTS_CLASS_METADATA_KIND_LIST = [0, 1, 2];
function getType(val) {
return Object.prototype.toString.call(val).slice(8, -1).toLowerCase();
}
function isPlainObject(val) {
if (val == null || typeof val !== 'object') {
return false;
}
const proto = Object.getPrototypeOf(val);
return proto === Object.prototype || proto === null;
}
// TODO 实现UTSError
class UTSError extends Error {
constructor(message) {
super(message);
}
}
function isUTSMetadata(metadata) {
return !!(metadata &&
UTS_CLASS_METADATA_KIND_LIST.includes(metadata.kind) &&
metadata.interfaces);
}
function isNativeType(proto) {
return !proto || proto === Object.prototype;
}
const utsMetadataKey = "$UTSMetadata$" /* IDENTIFIER.UTS_METADATA */;
/**
* 处理复杂的继承关系。
* 例如:
* class A extends abstract class B,abstract class B implements interface C
* new A() instanceof C -> true
*/
function getParentTypeList(type) {
const metadata = utsMetadataKey in type ? type[utsMetadataKey] : {};
let interfaces = [];
if (!isUTSMetadata(metadata)) {
interfaces = [];
}
else {
interfaces = metadata.interfaces || [];
}
const proto = Object.getPrototypeOf(type);
if (!isNativeType(proto)) {
interfaces.push(proto.constructor);
}
return interfaces;
}
function isImplementationOf(leftType, rightType, visited = []) {
if (isNativeType(leftType)) {
return false;
}
if (leftType === rightType) {
return true;
}
visited.push(leftType);
const parentTypeList = getParentTypeList(leftType);
return parentTypeList.some((parentType) => {
if (visited.includes(parentType)) {
return false;
}
return isImplementationOf(parentType, rightType, visited);
});
}
function isInstanceOf(value, type) {
if (type === UTSValueIterable) {
return value && value[Symbol.iterator];
}
const isNativeInstanceofType = value instanceof type;
if (isNativeInstanceofType || typeof value !== 'object' || value === null) {
return isNativeInstanceofType;
}
const proto = Object.getPrototypeOf(value).constructor;
return isImplementationOf(proto, type);
}
function isBaseType(type) {
return type === Number || type === String || type === Boolean;
}
function isUnknownType(type) {
return type === 'Unknown';
}
function isAnyType(type) {
return type === 'Any';
}
function isUTSType(type) {
return type && type.prototype && type.prototype instanceof UTSType;
}
function normalizeGenericValue(value, genericType, isJSONParse = false) {
return value == null
? null
: isBaseType(genericType) ||
isUnknownType(genericType) ||
isAnyType(genericType)
? value
: genericType === Array
? new Array(...value)
: new genericType(value, undefined, isJSONParse);
}
class UTSType {
static get$UTSMetadata$(...args) {
return {
name: '',
kind: 2 /* UTS_CLASS_METADATA_KIND.TYPE */,
interfaces: [],
fields: {},
};
}
get $UTSMetadata$() {
return UTSType.get$UTSMetadata$();
}
// TODO 缓存withGenerics结果
static withGenerics(parent, generics, isJSONParse = false) {
// 仅JSON.parse uni.request内报错,其他地方不报错
// generic类型为UTSType子类或Array或基础类型,否则报错
if (isJSONParse) {
const illegalGeneric = generics.find((item) => !(item === Array ||
isBaseType(item) ||
isUnknownType(item) ||
isAnyType(item) ||
item === UTSJSONObject ||
(item.prototype && item.prototype instanceof UTSType)));
if (illegalGeneric) {
throw new Error('Generic is not UTSType or Array or UTSJSONObject or base type, generic: ' +
illegalGeneric);
}
}
if (parent === Array) {
// 不带泛型的Array有一部分不会进入这里,需要在构造type时处理
return class UTSArray extends UTSType {
constructor(options, isJSONParse = false) {
if (!Array.isArray(options)) {
throw new UTSError(`Failed to contruct type, ${options} is not an array`);
}
super();
// @ts-expect-error
return options.map((item) => {
return normalizeGenericValue(item, generics[0], isJSONParse);
});
}
};
}
else if (parent === Map || parent === WeakMap) {
return class UTSMap extends UTSType {
constructor(options, isJSONParse = false) {
if (options == null || typeof options !== 'object') {
throw new UTSError(`Failed to contruct type, ${options} is not an object`);
}
super();
const obj = new parent();
for (const key in options) {
obj.set(normalizeGenericValue(key, generics[0], isJSONParse), normalizeGenericValue(options[key], generics[1], isJSONParse));
}
return obj;
}
};
}
else if (isUTSType(parent)) {
return class VirtualClassWithGenerics extends parent {
static get$UTSMetadata$() {
return parent.get$UTSMetadata$(...generics);
}
constructor(options, metadata = VirtualClassWithGenerics.get$UTSMetadata$(), isJSONParse = false) {
// @ts-expect-error
super(options, metadata, isJSONParse);
}
};
}
else {
return parent;
}
}
constructor() { }
static initProps(options, metadata, isJSONParse = false) {
// 为了性能,非JSON.parse场景直接返回
if (!isJSONParse) {
return options;
}
const obj = {};
if (!metadata.fields) {
return obj;
}
for (const key in metadata.fields) {
const { type, optional, jsonField } = metadata.fields[key];
const realKey = isJSONParse ? jsonField || key : key;
if (options[realKey] == null) {
if (optional) {
obj[key] = null;
continue;
}
else {
throw new UTSError(`Failed to contruct type, missing required property: ${key}`);
}
}
if (isUTSType(type)) {
// 带有泛型的数组会走此分支
obj[key] = isJSONParse
? // @ts-expect-error
new type(options[realKey], undefined, isJSONParse)
: options[realKey];
}
else if (type === Array) {
// 不带泛型的数组会走此分支
if (!Array.isArray(options[realKey])) {
throw new UTSError(`Failed to contruct type, property ${key} is not an array`);
}
obj[key] = options[realKey];
}
else {
obj[key] = options[realKey];
}
}
return obj;
}
}
function initUTSJSONObjectProperties(obj) {
const propertyList = [
'_resolveKeyPath',
'_getValue',
'toJSON',
'get',
'set',
'getAny',
'getString',
'getNumber',
'getBoolean',
'getJSON',
'getArray',
'toMap',
'forEach',
];
const propertyDescriptorMap = {};
for (let i = 0; i < propertyList.length; i++) {
const property = propertyList[i];
propertyDescriptorMap[property] = {
enumerable: false,
value: obj[property],
};
}
Object.defineProperties(obj, propertyDescriptorMap);
}
function getRealDefaultValue(defaultValue) {
return defaultValue === void 0 ? null : defaultValue;
}
class UTSJSONObject {
static keys(obj) {
return Object.keys(obj);
}
static assign(target, ...sources) {
for (let i = 0; i < sources.length; i++) {
const source = sources[i];
for (let key in source) {
target[key] = source[key];
}
}
return target;
}
constructor(content = {}) {
if (content instanceof Map) {
content.forEach((value, key) => {
this[key] = value;
});
}
else {
for (const key in content) {
if (Object.prototype.hasOwnProperty.call(content, key)) {
this[key] = content[key];
}
}
}
initUTSJSONObjectProperties(this);
}
_resolveKeyPath(keyPath) {
// 非法keyPath不抛出错误,直接返回空数组
let token = '';
const keyPathArr = [];
let inOpenParentheses = false;
for (let i = 0; i < keyPath.length; i++) {
const word = keyPath[i];
switch (word) {
case '.':
if (token.length > 0) {
keyPathArr.push(token);
token = '';
}
break;
case '[': {
inOpenParentheses = true;
if (token.length > 0) {
keyPathArr.push(token);
token = '';
}
break;
}
case ']':
if (inOpenParentheses) {
if (token.length > 0) {
const tokenFirstChar = token[0];
const tokenLastChar = token[token.length - 1];
if ((tokenFirstChar === '"' && tokenLastChar === '"') ||
(tokenFirstChar === "'" && tokenLastChar === "'") ||
(tokenFirstChar === '`' && tokenLastChar === '`')) {
if (token.length > 2) {
token = token.slice(1, -1);
}
else {
return [];
}
}
else if (!/^\d+$/.test(token)) {
return [];
}
keyPathArr.push(token);
token = '';
}
else {
return [];
}
inOpenParentheses = false;
}
else {
return [];
}
break;
default:
token += word;
break;
}
if (i === keyPath.length - 1) {
if (token.length > 0) {
keyPathArr.push(token);
token = '';
}
}
}
return keyPathArr;
}
_getValue(keyPath, defaultValue) {
const keyPathArr = this._resolveKeyPath(keyPath);
const realDefaultValue = getRealDefaultValue(defaultValue);
if (keyPathArr.length === 0) {
return realDefaultValue;
}
let value = this;
for (let i = 0; i < keyPathArr.length; i++) {
const key = keyPathArr[i];
if (value instanceof Object) {
if (key in value) {
value = value[key];
}
else {
return realDefaultValue;
}
}
else {
return realDefaultValue;
}
}
return value;
}
get(key) {
return this._getValue(key);
}
set(key, value) {
this[key] = value;
}
getAny(key, defaultValue) {
const realDefaultValue = getRealDefaultValue(defaultValue);
return this._getValue(key, realDefaultValue);
}
getString(key, defaultValue) {
const realDefaultValue = getRealDefaultValue(defaultValue);
const value = this._getValue(key, realDefaultValue);
if (typeof value === 'string') {
return value;
}
else {
return realDefaultValue;
}
}
getNumber(key, defaultValue) {
const realDefaultValue = getRealDefaultValue(defaultValue);
const value = this._getValue(key, realDefaultValue);
if (typeof value === 'number') {
return value;
}
else {
return realDefaultValue;
}
}
getBoolean(key, defaultValue) {
const realDefaultValue = getRealDefaultValue(defaultValue);
const boolean = this._getValue(key, realDefaultValue);
if (typeof boolean === 'boolean') {
return boolean;
}
else {
return realDefaultValue;
}
}
getJSON(key, defaultValue) {
const realDefaultValue = getRealDefaultValue(defaultValue);
let value = this._getValue(key, realDefaultValue);
if (value instanceof Object) {
return value;
}
else {
return realDefaultValue;
}
}
getArray(key, defaultValue) {
const realDefaultValue = getRealDefaultValue(defaultValue);
let value = this._getValue(key, realDefaultValue);
if (value instanceof Array) {
return value;
}
else {
return realDefaultValue;
}
}
toMap() {
let map = new Map();
for (let key in this) {
map.set(key, this[key]);
}
return map;
}
forEach(callback) {
for (let key in this) {
callback(this[key], key);
}
}
}
const OriginalJSON = JSON;
function createUTSJSONObjectOrArray(obj) {
if (Array.isArray(obj)) {
return obj.map((item) => {
return createUTSJSONObjectOrArray(item);
});
}
else if (isPlainObject(obj)) {
const result = new UTSJSONObject({});
for (const key in obj) {
const value = obj[key];
result[key] = createUTSJSONObjectOrArray(value);
}
return result;
}
return obj;
}
function parseObjectOrArray(object, utsType) {
const objectType = getType(object);
if (object === null || (objectType !== 'object' && objectType !== 'array')) {
return object;
}
if (utsType && utsType !== UTSJSONObject) {
try {
return new utsType(object, undefined, true);
}
catch (error) {
console.error(error);
return null;
}
}
if (objectType === 'array' || objectType === 'object') {
return createUTSJSONObjectOrArray(object);
}
return object;
}
const UTSJSON = {
parse: (text, reviver, utsType) => {
// @ts-expect-error
if (reviver && (isUTSType(reviver) || reviver === UTSJSONObject)) {
utsType = reviver;
reviver = undefined;
}
try {
const parseResult = OriginalJSON.parse(text, reviver);
return parseObjectOrArray(parseResult, utsType);
}
catch (error) {
console.error(error);
return null;
}
},
parseArray(text, utsType) {
try {
const parseResult = OriginalJSON.parse(text);
if (Array.isArray(parseResult)) {
return parseObjectOrArray(parseResult, utsType ? UTSType.withGenerics(Array, [utsType], true) : undefined);
}
return null;
}
catch (error) {
console.error(error);
return null;
}
},
parseObject(text, utsType) {
try {
const parseResult = OriginalJSON.parse(text);
if (Array.isArray(parseResult)) {
return null;
}
return parseObjectOrArray(parseResult, utsType);
}
catch (error) {
console.error(error);
return null;
}
},
stringify: (value, replacer, space) => {
try {
if (!replacer) {
const visited = new Set();
replacer = function (_, v) {
if (typeof v === 'object') {
if (visited.has(v)) {
return null;
}
visited.add(v);
}
return v;
};
}
return OriginalJSON.stringify(value, replacer, space);
}
catch (error) {
console.error(error);
return '';
}
},
};
function mapGet(map, key) {
if (!map.has(key)) {
return null;
}
return map.get(key);
}
function stringCodePointAt(str, pos) {
if (pos < 0 || pos >= str.length) {
return null;
}
return str.codePointAt(pos);
}
function stringAt(str, pos) {
if (pos < -str.length || pos >= str.length) {
return null;
}
return str.at(pos);
}
function weakMapGet(map, key) {
if (!map.has(key)) {
return null;
}
return map.get(key);
}
const UTS = {
arrayAt,
arrayFind,
arrayFindLast,
arrayPop,
arrayShift,
isInstanceOf,
UTSType,
mapGet,
stringAt,
stringCodePointAt,
weakMapGet,
JSON: UTSJSON,
};
class UniError extends Error {
constructor(errSubject, errCode, errMsg) {
let options = {};
const argsLength = Array.from(arguments).length;
switch (argsLength) {
case 0:
errSubject = '';
errMsg = '';
errCode = 0;
break;
case 1:
errMsg = errSubject;
errSubject = '';
errCode = 0;
break;
case 2:
errMsg = errSubject;
options = errCode;
errCode = options.errCode || 0;
errSubject = options.errSubject || '';
break;
}
super(errMsg);
this.name = 'UniError';
this.errSubject = errSubject;
this.errCode = errCode;
this.errMsg = errMsg;
if (options.data) {
this.data = options.data;
}
if (options.cause) {
this.cause = options.cause;
}
}
set errMsg(msg) {
this.message = msg;
}
get errMsg() {
return this.message;
}
toString() {
return this.errMsg;
}
toJSON() {
return {
errSubject: this.errSubject,
errCode: this.errCode,
errMsg: this.errMsg,
data: this.data,
cause: this.cause && typeof this.cause.toJSON === 'function'
? this.cause.toJSON()
: this.cause,
};
}
}
class UTSValueIterable {
}
function getGlobalOnce() {
if (typeof globalThis !== 'undefined') {
return globalThis;
}
// worker
if (typeof self !== 'undefined') {
return self;
}
// browser
if (typeof window !== 'undefined') {
return window;
}
// nodejs
// if (typeof global !== 'undefined') {
// return global
// }
function g() {
return this;
}
if (typeof g() !== 'undefined') {
return g();
}
return (function () {
return new Function('return this')();
})();
}
let g = undefined;
function getGlobal() {
if (g) {
return g;
}
g = getGlobalOnce();
return g;
}
const realGlobal = getGlobal();
realGlobal.UTS = UTS;
realGlobal.UTSJSONObject = UTSJSONObject;
realGlobal.UTSValueIterable = UTSValueIterable;
realGlobal.UniError = UniError;
class WorkerTaskImpl {
constructor() {
{
worker.onMessage((e) => {
this.onMessage(e);
});
}
}
entry() { }
onMessage(message) { }
postMessage(message, options = null) {
{
worker.postMessage(message);
}
}
}
// @ts-expect-error
globalThis.WorkerTaskImpl = WorkerTaskImpl;
exports.UTS = UTS;
exports.UTSJSONObject = UTSJSONObject;
exports.UTSValueIterable = UTSValueIterable;
exports.UniError = UniError;
exports.WorkerTaskImpl = WorkerTaskImpl;
return exports;
})({});
+751
View File
@@ -0,0 +1,751 @@
(function (exports) {
'raw js';
'use strict';
function arrayPop(array) {
if (array.length === 0) {
return null;
}
return array.pop();
}
function arrayShift(array) {
if (array.length === 0) {
return null;
}
return array.shift();
}
function arrayFind(array, predicate) {
const index = array.findIndex(predicate);
if (index < 0) {
return null;
}
return array[index];
}
function arrayFindLast(array, predicate) {
const index = array.findLastIndex(predicate);
if (index < 0) {
return null;
}
return array[index];
}
function arrayAt(array, index) {
if (index < -array.length || index >= array.length) {
return null;
}
return array.at(index);
}
/**
* copy from @uts/shared
*/
const UTS_CLASS_METADATA_KIND_LIST = [0, 1, 2];
function getType(val) {
return Object.prototype.toString.call(val).slice(8, -1).toLowerCase();
}
function isPlainObject(val) {
if (val == null || typeof val !== 'object') {
return false;
}
const proto = Object.getPrototypeOf(val);
return proto === Object.prototype || proto === null;
}
// TODO 实现UTSError
class UTSError extends Error {
constructor(message) {
super(message);
}
}
function isUTSMetadata(metadata) {
return !!(metadata &&
UTS_CLASS_METADATA_KIND_LIST.includes(metadata.kind) &&
metadata.interfaces);
}
function isNativeType(proto) {
return !proto || proto === Object.prototype;
}
const utsMetadataKey = "$UTSMetadata$" /* IDENTIFIER.UTS_METADATA */;
/**
* 处理复杂的继承关系。
* 例如:
* class A extends abstract class B,abstract class B implements interface C
* new A() instanceof C -> true
*/
function getParentTypeList(type) {
const metadata = utsMetadataKey in type ? type[utsMetadataKey] : {};
let interfaces = [];
if (!isUTSMetadata(metadata)) {
interfaces = [];
}
else {
interfaces = metadata.interfaces || [];
}
const proto = Object.getPrototypeOf(type);
if (!isNativeType(proto)) {
interfaces.push(proto.constructor);
}
return interfaces;
}
function isImplementationOf(leftType, rightType, visited = []) {
if (isNativeType(leftType)) {
return false;
}
if (leftType === rightType) {
return true;
}
visited.push(leftType);
const parentTypeList = getParentTypeList(leftType);
return parentTypeList.some((parentType) => {
if (visited.includes(parentType)) {
return false;
}
return isImplementationOf(parentType, rightType, visited);
});
}
function isInstanceOf(value, type) {
if (type === UTSValueIterable) {
return value && value[Symbol.iterator];
}
const isNativeInstanceofType = value instanceof type;
if (isNativeInstanceofType || typeof value !== 'object' || value === null) {
return isNativeInstanceofType;
}
const proto = Object.getPrototypeOf(value).constructor;
return isImplementationOf(proto, type);
}
function isBaseType(type) {
return type === Number || type === String || type === Boolean;
}
function isUnknownType(type) {
return type === 'Unknown';
}
function isAnyType(type) {
return type === 'Any';
}
function isUTSType(type) {
return type && type.prototype && type.prototype instanceof UTSType;
}
function normalizeGenericValue(value, genericType, isJSONParse = false) {
return value == null
? null
: isBaseType(genericType) ||
isUnknownType(genericType) ||
isAnyType(genericType)
? value
: genericType === Array
? new Array(...value)
: new genericType(value, undefined, isJSONParse);
}
class UTSType {
static get$UTSMetadata$(...args) {
return {
name: '',
kind: 2 /* UTS_CLASS_METADATA_KIND.TYPE */,
interfaces: [],
fields: {},
};
}
get $UTSMetadata$() {
return UTSType.get$UTSMetadata$();
}
// TODO 缓存withGenerics结果
static withGenerics(parent, generics, isJSONParse = false) {
// 仅JSON.parse uni.request内报错,其他地方不报错
// generic类型为UTSType子类或Array或基础类型,否则报错
if (isJSONParse) {
const illegalGeneric = generics.find((item) => !(item === Array ||
isBaseType(item) ||
isUnknownType(item) ||
isAnyType(item) ||
item === UTSJSONObject ||
(item.prototype && item.prototype instanceof UTSType)));
if (illegalGeneric) {
throw new Error('Generic is not UTSType or Array or UTSJSONObject or base type, generic: ' +
illegalGeneric);
}
}
if (parent === Array) {
// 不带泛型的Array有一部分不会进入这里,需要在构造type时处理
return class UTSArray extends UTSType {
constructor(options, isJSONParse = false) {
if (!Array.isArray(options)) {
throw new UTSError(`Failed to contruct type, ${options} is not an array`);
}
super();
// @ts-expect-error
return options.map((item) => {
return normalizeGenericValue(item, generics[0], isJSONParse);
});
}
};
}
else if (parent === Map || parent === WeakMap) {
return class UTSMap extends UTSType {
constructor(options, isJSONParse = false) {
if (options == null || typeof options !== 'object') {
throw new UTSError(`Failed to contruct type, ${options} is not an object`);
}
super();
const obj = new parent();
for (const key in options) {
obj.set(normalizeGenericValue(key, generics[0], isJSONParse), normalizeGenericValue(options[key], generics[1], isJSONParse));
}
return obj;
}
};
}
else if (isUTSType(parent)) {
return class VirtualClassWithGenerics extends parent {
static get$UTSMetadata$() {
return parent.get$UTSMetadata$(...generics);
}
constructor(options, metadata = VirtualClassWithGenerics.get$UTSMetadata$(), isJSONParse = false) {
// @ts-expect-error
super(options, metadata, isJSONParse);
}
};
}
else {
return parent;
}
}
constructor() { }
static initProps(options, metadata, isJSONParse = false) {
// 为了性能,非JSON.parse场景直接返回
if (!isJSONParse) {
return options;
}
const obj = {};
if (!metadata.fields) {
return obj;
}
for (const key in metadata.fields) {
const { type, optional, jsonField } = metadata.fields[key];
const realKey = isJSONParse ? jsonField || key : key;
if (options[realKey] == null) {
if (optional) {
obj[key] = null;
continue;
}
else {
throw new UTSError(`Failed to contruct type, missing required property: ${key}`);
}
}
if (isUTSType(type)) {
// 带有泛型的数组会走此分支
obj[key] = isJSONParse
? // @ts-expect-error
new type(options[realKey], undefined, isJSONParse)
: options[realKey];
}
else if (type === Array) {
// 不带泛型的数组会走此分支
if (!Array.isArray(options[realKey])) {
throw new UTSError(`Failed to contruct type, property ${key} is not an array`);
}
obj[key] = options[realKey];
}
else {
obj[key] = options[realKey];
}
}
return obj;
}
}
function initUTSJSONObjectProperties(obj) {
const propertyList = [
'_resolveKeyPath',
'_getValue',
'toJSON',
'get',
'set',
'getAny',
'getString',
'getNumber',
'getBoolean',
'getJSON',
'getArray',
'toMap',
'forEach',
];
const propertyDescriptorMap = {};
for (let i = 0; i < propertyList.length; i++) {
const property = propertyList[i];
propertyDescriptorMap[property] = {
enumerable: false,
value: obj[property],
};
}
Object.defineProperties(obj, propertyDescriptorMap);
}
function getRealDefaultValue(defaultValue) {
return defaultValue === void 0 ? null : defaultValue;
}
class UTSJSONObject {
static keys(obj) {
return Object.keys(obj);
}
static assign(target, ...sources) {
for (let i = 0; i < sources.length; i++) {
const source = sources[i];
for (let key in source) {
target[key] = source[key];
}
}
return target;
}
constructor(content = {}) {
if (content instanceof Map) {
content.forEach((value, key) => {
this[key] = value;
});
}
else {
for (const key in content) {
if (Object.prototype.hasOwnProperty.call(content, key)) {
this[key] = content[key];
}
}
}
initUTSJSONObjectProperties(this);
}
_resolveKeyPath(keyPath) {
// 非法keyPath不抛出错误,直接返回空数组
let token = '';
const keyPathArr = [];
let inOpenParentheses = false;
for (let i = 0; i < keyPath.length; i++) {
const word = keyPath[i];
switch (word) {
case '.':
if (token.length > 0) {
keyPathArr.push(token);
token = '';
}
break;
case '[': {
inOpenParentheses = true;
if (token.length > 0) {
keyPathArr.push(token);
token = '';
}
break;
}
case ']':
if (inOpenParentheses) {
if (token.length > 0) {
const tokenFirstChar = token[0];
const tokenLastChar = token[token.length - 1];
if ((tokenFirstChar === '"' && tokenLastChar === '"') ||
(tokenFirstChar === "'" && tokenLastChar === "'") ||
(tokenFirstChar === '`' && tokenLastChar === '`')) {
if (token.length > 2) {
token = token.slice(1, -1);
}
else {
return [];
}
}
else if (!/^\d+$/.test(token)) {
return [];
}
keyPathArr.push(token);
token = '';
}
else {
return [];
}
inOpenParentheses = false;
}
else {
return [];
}
break;
default:
token += word;
break;
}
if (i === keyPath.length - 1) {
if (token.length > 0) {
keyPathArr.push(token);
token = '';
}
}
}
return keyPathArr;
}
_getValue(keyPath, defaultValue) {
const keyPathArr = this._resolveKeyPath(keyPath);
const realDefaultValue = getRealDefaultValue(defaultValue);
if (keyPathArr.length === 0) {
return realDefaultValue;
}
let value = this;
for (let i = 0; i < keyPathArr.length; i++) {
const key = keyPathArr[i];
if (value instanceof Object) {
if (key in value) {
value = value[key];
}
else {
return realDefaultValue;
}
}
else {
return realDefaultValue;
}
}
return value;
}
get(key) {
return this._getValue(key);
}
set(key, value) {
this[key] = value;
}
getAny(key, defaultValue) {
const realDefaultValue = getRealDefaultValue(defaultValue);
return this._getValue(key, realDefaultValue);
}
getString(key, defaultValue) {
const realDefaultValue = getRealDefaultValue(defaultValue);
const value = this._getValue(key, realDefaultValue);
if (typeof value === 'string') {
return value;
}
else {
return realDefaultValue;
}
}
getNumber(key, defaultValue) {
const realDefaultValue = getRealDefaultValue(defaultValue);
const value = this._getValue(key, realDefaultValue);
if (typeof value === 'number') {
return value;
}
else {
return realDefaultValue;
}
}
getBoolean(key, defaultValue) {
const realDefaultValue = getRealDefaultValue(defaultValue);
const boolean = this._getValue(key, realDefaultValue);
if (typeof boolean === 'boolean') {
return boolean;
}
else {
return realDefaultValue;
}
}
getJSON(key, defaultValue) {
const realDefaultValue = getRealDefaultValue(defaultValue);
let value = this._getValue(key, realDefaultValue);
if (value instanceof Object) {
return value;
}
else {
return realDefaultValue;
}
}
getArray(key, defaultValue) {
const realDefaultValue = getRealDefaultValue(defaultValue);
let value = this._getValue(key, realDefaultValue);
if (value instanceof Array) {
return value;
}
else {
return realDefaultValue;
}
}
toMap() {
let map = new Map();
for (let key in this) {
map.set(key, this[key]);
}
return map;
}
forEach(callback) {
for (let key in this) {
callback(this[key], key);
}
}
}
const OriginalJSON = JSON;
function createUTSJSONObjectOrArray(obj) {
if (Array.isArray(obj)) {
return obj.map((item) => {
return createUTSJSONObjectOrArray(item);
});
}
else if (isPlainObject(obj)) {
const result = new UTSJSONObject({});
for (const key in obj) {
const value = obj[key];
result[key] = createUTSJSONObjectOrArray(value);
}
return result;
}
return obj;
}
function parseObjectOrArray(object, utsType) {
const objectType = getType(object);
if (object === null || (objectType !== 'object' && objectType !== 'array')) {
return object;
}
if (utsType && utsType !== UTSJSONObject) {
try {
return new utsType(object, undefined, true);
}
catch (error) {
console.error(error);
return null;
}
}
if (objectType === 'array' || objectType === 'object') {
return createUTSJSONObjectOrArray(object);
}
return object;
}
const UTSJSON = {
parse: (text, reviver, utsType) => {
// @ts-expect-error
if (reviver && (isUTSType(reviver) || reviver === UTSJSONObject)) {
utsType = reviver;
reviver = undefined;
}
try {
const parseResult = OriginalJSON.parse(text, reviver);
return parseObjectOrArray(parseResult, utsType);
}
catch (error) {
console.error(error);
return null;
}
},
parseArray(text, utsType) {
try {
const parseResult = OriginalJSON.parse(text);
if (Array.isArray(parseResult)) {
return parseObjectOrArray(parseResult, utsType ? UTSType.withGenerics(Array, [utsType], true) : undefined);
}
return null;
}
catch (error) {
console.error(error);
return null;
}
},
parseObject(text, utsType) {
try {
const parseResult = OriginalJSON.parse(text);
if (Array.isArray(parseResult)) {
return null;
}
return parseObjectOrArray(parseResult, utsType);
}
catch (error) {
console.error(error);
return null;
}
},
stringify: (value, replacer, space) => {
try {
if (!replacer) {
const visited = new Set();
replacer = function (_, v) {
if (typeof v === 'object') {
if (visited.has(v)) {
return null;
}
visited.add(v);
}
return v;
};
}
return OriginalJSON.stringify(value, replacer, space);
}
catch (error) {
console.error(error);
return '';
}
},
};
function mapGet(map, key) {
if (!map.has(key)) {
return null;
}
return map.get(key);
}
function stringCodePointAt(str, pos) {
if (pos < 0 || pos >= str.length) {
return null;
}
return str.codePointAt(pos);
}
function stringAt(str, pos) {
if (pos < -str.length || pos >= str.length) {
return null;
}
return str.at(pos);
}
function weakMapGet(map, key) {
if (!map.has(key)) {
return null;
}
return map.get(key);
}
const UTS = {
arrayAt,
arrayFind,
arrayFindLast,
arrayPop,
arrayShift,
isInstanceOf,
UTSType,
mapGet,
stringAt,
stringCodePointAt,
weakMapGet,
JSON: UTSJSON,
};
class UniError extends Error {
constructor(errSubject, errCode, errMsg) {
let options = {};
const argsLength = Array.from(arguments).length;
switch (argsLength) {
case 0:
errSubject = '';
errMsg = '';
errCode = 0;
break;
case 1:
errMsg = errSubject;
errSubject = '';
errCode = 0;
break;
case 2:
errMsg = errSubject;
options = errCode;
errCode = options.errCode || 0;
errSubject = options.errSubject || '';
break;
}
super(errMsg);
this.name = 'UniError';
this.errSubject = errSubject;
this.errCode = errCode;
this.errMsg = errMsg;
if (options.data) {
this.data = options.data;
}
if (options.cause) {
this.cause = options.cause;
}
}
set errMsg(msg) {
this.message = msg;
}
get errMsg() {
return this.message;
}
toString() {
return this.errMsg;
}
toJSON() {
return {
errSubject: this.errSubject,
errCode: this.errCode,
errMsg: this.errMsg,
data: this.data,
cause: this.cause && typeof this.cause.toJSON === 'function'
? this.cause.toJSON()
: this.cause,
};
}
}
class UTSValueIterable {
}
function getGlobalOnce() {
if (typeof globalThis !== 'undefined') {
return globalThis;
}
// worker
if (typeof self !== 'undefined') {
return self;
}
// browser
if (typeof window !== 'undefined') {
return window;
}
// nodejs
// if (typeof global !== 'undefined') {
// return global
// }
function g() {
return this;
}
if (typeof g() !== 'undefined') {
return g();
}
return (function () {
return new Function('return this')();
})();
}
let g = undefined;
function getGlobal() {
if (g) {
return g;
}
g = getGlobalOnce();
return g;
}
const realGlobal = getGlobal();
realGlobal.UTS = UTS;
realGlobal.UTSJSONObject = UTSJSONObject;
realGlobal.UTSValueIterable = UTSValueIterable;
realGlobal.UniError = UniError;
class WorkerTaskImpl {
constructor() {
{
self.onmessage = (e) => {
this.onMessage(e.data);
};
}
}
entry() { }
onMessage(message) { }
postMessage(message, options = null) {
{
let _options = undefined;
if ((options === null || options === void 0 ? void 0 : options.transfer) && options.transfer.length > 0) {
_options = {
transfer: options.transfer,
};
}
self.postMessage(message, _options);
}
}
}
// @ts-expect-error
globalThis.WorkerTaskImpl = WorkerTaskImpl;
exports.UTS = UTS;
exports.UTSJSONObject = UTSJSONObject;
exports.UTSValueIterable = UTSValueIterable;
exports.UniError = UniError;
exports.WorkerTaskImpl = WorkerTaskImpl;
return exports;
})({});
+230
View File
@@ -0,0 +1,230 @@
'use strict';
var vue = require('vue');
var shared = require('@vue/shared');
var uniShared = require('@dcloudio/uni-shared');
function assertKey(key, shallow = false) {
if (!key) {
throw new Error(`${shallow ? 'shallowSsrRef' : 'ssrRef'}: You must provide a key.`);
}
}
function proxy(target, track, trigger) {
return new Proxy(target, {
get(target, prop) {
track();
if (shared.isObject(target[prop])) {
return proxy(target[prop], track, trigger);
}
return Reflect.get(target, prop);
},
set(obj, prop, newVal) {
const result = Reflect.set(obj, prop, newVal);
trigger();
return result;
},
});
}
const globalData = {};
const ssrServerRef = (value, key, shallow = false) => {
assertKey(key, shallow);
const ctx = vue.getCurrentInstance() && vue.useSSRContext();
let state;
if (ctx) {
const __uniSSR = ctx[uniShared.UNI_SSR] || (ctx[uniShared.UNI_SSR] = {});
state = __uniSSR[uniShared.UNI_SSR_DATA] || (__uniSSR[uniShared.UNI_SSR_DATA] = {});
}
else {
state = globalData;
}
state[key] = uniShared.sanitise(value);
// SSR 模式下 watchEffect 不生效 https://github.com/vuejs/vue-next/blob/master/packages/runtime-core/src/apiWatch.ts#L283
// 故自定义ref
return vue.customRef((track, trigger) => {
const customTrigger = () => (trigger(), (state[key] = uniShared.sanitise(value)));
return {
get: () => {
track();
if (!shallow && shared.isObject(value)) {
return proxy(value, track, customTrigger);
}
return value;
},
set: (v) => {
value = v;
customTrigger();
},
};
});
};
const ssrRef = (value, key) => {
{
return ssrServerRef(value, key);
}
};
const shallowSsrRef = (value, key) => {
{
return ssrServerRef(value, key, true);
}
};
function getSsrGlobalData() {
return uniShared.sanitise(globalData);
}
/**
* uni 对象是跨实例的,而此处列的 API 均是需要跟当前实例关联的,比如 requireNativePlugin 获取 dom 时,依赖当前 weex 实例
*/
function getCurrentSubNVue() {
return uni.getSubNVueById(plus.webview.currentWebview().id);
}
function requireNativePlugin(name) {
return weex.requireModule(name);
}
function formatAppLog(type, filename, ...args) {
// @ts-expect-error
if (uni.__log__) {
// @ts-expect-error
uni.__log__(type, filename, ...args);
}
else {
console[type].apply(console, [...args, filename]);
}
}
function formatLog(type, filename, ...args) {
if (filename) {
args.push(filename);
}
console[type].apply(console, args);
}
function resolveEasycom(component, easycom) {
return typeof component === 'string' ? easycom : component;
}
/// <reference types="@dcloudio/types" />
// function isUniPage(target: ComponentInternalInstance | null): boolean {
// if (target && 'renderer' in target) {
// return target.renderer === 'page'
// }
// return true
// }
const createLifeCycleHook = (lifecycle, flag = 0 /* HookFlags.UNKNOWN */) => (hook, target = vue.getCurrentInstance()) => {
if (vue.isInSSRComponentSetup)
return;
// post-create lifecycle registrations are noops during SSR
vue.injectHook(lifecycle, hook, target);
};
const onAppShow = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_SHOW, 1 /* HookFlags.APP */);
const onAppHide = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_HIDE, 1 /* HookFlags.APP */);
const onShow = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_SHOW, 2 /* HookFlags.PAGE */);
const onHide = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_HIDE, 2 /* HookFlags.PAGE */);
const onLaunch = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_LAUNCH, 1 /* HookFlags.APP */);
const onError = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_ERROR, 1 /* HookFlags.APP */);
const onThemeChange = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_THEME_CHANGE, 1 /* HookFlags.APP */);
const onPageNotFound = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_PAGE_NOT_FOUND, 1 /* HookFlags.APP */);
const onUnhandledRejection = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_UNHANDLE_REJECTION, 1 /* HookFlags.APP */);
const onLastPageBackPress = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_LAST_PAGE_BACK_PRESS, 1 /* HookFlags.APP */);
const onExit = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_EXIT, 1 /* HookFlags.APP */);
const onInit = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_INIT, 2 /* HookFlags.PAGE */ | 4 /* HookFlags.COMPONENT */);
// 小程序如果想在 setup 的 props 传递页面参数,需要定义 props,故同时暴露 onLoad 吧
const onLoad = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_LOAD, 2 /* HookFlags.PAGE */);
const onReady = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_READY, 2 /* HookFlags.PAGE */);
const onUnload = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_UNLOAD, 2 /* HookFlags.PAGE */);
const onResize = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_RESIZE, 2 /* HookFlags.PAGE */);
const onBackPress = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_BACK_PRESS, 2 /* HookFlags.PAGE */);
const onPageScroll = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_PAGE_SCROLL, 2 /* HookFlags.PAGE */);
const onTabItemTap = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_TAB_ITEM_TAP, 2 /* HookFlags.PAGE */);
const onReachBottom = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_REACH_BOTTOM, 2 /* HookFlags.PAGE */);
const onPullDownRefresh = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_PULL_DOWN_REFRESH, 2 /* HookFlags.PAGE */);
const onSaveExitState =
/*#__PURE__*/ createLifeCycleHook(uniShared.ON_SAVE_EXIT_STATE, 2 /* HookFlags.PAGE */);
const onTitleClick = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_TITLE_CLICK, 2 /* HookFlags.PAGE */);
const onShareTimeline = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_SHARE_TIMELINE, 2 /* HookFlags.PAGE */);
const onShareChat = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_SHARE_CHAT, 2 /* HookFlags.PAGE */);
const onAddToFavorites = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_ADD_TO_FAVORITES, 2 /* HookFlags.PAGE */);
const onShareAppMessage = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_SHARE_APP_MESSAGE, 2 /* HookFlags.PAGE */);
const onCopyUrl = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_COPY_URL, 2 /* HookFlags.PAGE */);
const onUploadDouyinVideo = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_UPLOAD_DOUYIN_VIDEO, 2 /* HookFlags.PAGE */);
const onLiveMount = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_LIVE_MOUNT, 2 /* HookFlags.PAGE */);
const onNavigationBarButtonTap = /*#__PURE__*/ createLifeCycleHook(uniShared.ON_NAVIGATION_BAR_BUTTON_TAP, 2 /* HookFlags.PAGE */);
const onNavigationBarSearchInputChanged =
/*#__PURE__*/ createLifeCycleHook(uniShared.ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED, 2 /* HookFlags.PAGE */);
const onNavigationBarSearchInputClicked =
/*#__PURE__*/ createLifeCycleHook(uniShared.ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED, 2 /* HookFlags.PAGE */);
const onNavigationBarSearchInputConfirmed =
/*#__PURE__*/ createLifeCycleHook(uniShared.ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED, 2 /* HookFlags.PAGE */);
const onNavigationBarSearchInputFocusChanged =
/*#__PURE__*/ createLifeCycleHook(uniShared.ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED, 2 /* HookFlags.PAGE */);
const onPageShow = onShow;
const onPageHide = onHide;
function renderComponentSlot(slots, name, props = null) {
if (slots[name]) {
return slots[name](props);
}
return null;
}
Object.defineProperty(exports, "capitalize", {
enumerable: true,
get: function () { return shared.capitalize; }
});
Object.defineProperty(exports, "extend", {
enumerable: true,
get: function () { return shared.extend; }
});
Object.defineProperty(exports, "hasOwn", {
enumerable: true,
get: function () { return shared.hasOwn; }
});
Object.defineProperty(exports, "isPlainObject", {
enumerable: true,
get: function () { return shared.isPlainObject; }
});
exports.formatAppLog = formatAppLog;
exports.formatLog = formatLog;
exports.getCurrentSubNVue = getCurrentSubNVue;
exports.getSsrGlobalData = getSsrGlobalData;
exports.onAddToFavorites = onAddToFavorites;
exports.onAppHide = onAppHide;
exports.onAppShow = onAppShow;
exports.onBackPress = onBackPress;
exports.onCopyUrl = onCopyUrl;
exports.onError = onError;
exports.onExit = onExit;
exports.onHide = onHide;
exports.onInit = onInit;
exports.onLastPageBackPress = onLastPageBackPress;
exports.onLaunch = onLaunch;
exports.onLiveMount = onLiveMount;
exports.onLoad = onLoad;
exports.onNavigationBarButtonTap = onNavigationBarButtonTap;
exports.onNavigationBarSearchInputChanged = onNavigationBarSearchInputChanged;
exports.onNavigationBarSearchInputClicked = onNavigationBarSearchInputClicked;
exports.onNavigationBarSearchInputConfirmed = onNavigationBarSearchInputConfirmed;
exports.onNavigationBarSearchInputFocusChanged = onNavigationBarSearchInputFocusChanged;
exports.onPageHide = onPageHide;
exports.onPageNotFound = onPageNotFound;
exports.onPageScroll = onPageScroll;
exports.onPageShow = onPageShow;
exports.onPullDownRefresh = onPullDownRefresh;
exports.onReachBottom = onReachBottom;
exports.onReady = onReady;
exports.onResize = onResize;
exports.onSaveExitState = onSaveExitState;
exports.onShareAppMessage = onShareAppMessage;
exports.onShareChat = onShareChat;
exports.onShareTimeline = onShareTimeline;
exports.onShow = onShow;
exports.onTabItemTap = onTabItemTap;
exports.onThemeChange = onThemeChange;
exports.onTitleClick = onTitleClick;
exports.onUnhandledRejection = onUnhandledRejection;
exports.onUnload = onUnload;
exports.onUploadDouyinVideo = onUploadDouyinVideo;
exports.renderComponentSlot = renderComponentSlot;
exports.requireNativePlugin = requireNativePlugin;
exports.resolveEasycom = resolveEasycom;
exports.shallowSsrRef = shallowSsrRef;
exports.ssrRef = ssrRef;
+138
View File
@@ -0,0 +1,138 @@
/// <reference types="@dcloudio/types" />
import { capitalize } from '@vue/shared';
import type { ComponentInternalInstance } from 'vue';
import { extend } from '@vue/shared';
import { hasOwn } from '@vue/shared';
import { isPlainObject } from '@vue/shared';
import { ref } from 'vue';
import { shallowRef } from 'vue';
import type { Slots } from 'vue';
export { capitalize }
export { extend }
export declare function formatAppLog(type: 'log' | 'info' | 'debug' | 'warn' | 'error', filename: string, ...args: unknown[]): void;
export declare function formatLog(type: keyof Console, filename: string, ...args: unknown[]): void;
/**
* uni 对象是跨实例的,而此处列的 API 均是需要跟当前实例关联的,比如 requireNativePlugin 获取 dom 时,依赖当前 weex 实例
*/
/// <reference types="@dcloudio/types" />
export declare function getCurrentSubNVue(): UniApp.SubNVue;
export declare function getSsrGlobalData(): any;
export { hasOwn }
export declare const enum HookFlags {
UNKNOWN = 0,
APP = 1,
PAGE = 2,
COMPONENT = 4
}
export { isPlainObject }
declare interface NavigationBarSearchInputFocusChanged {
focus: boolean;
}
export declare const onAddToFavorites: (hook: (options: Page.AddToFavoritesOption) => Page.CustomFavoritesContent, target?: ComponentInternalInstance | null) => void;
export declare const onAppHide: (hook: () => any, target?: ComponentInternalInstance | null) => void;
export declare const onAppShow: (hook: (options?: App.LaunchShowOption | undefined) => void, target?: ComponentInternalInstance | null) => void;
export declare const onBackPress: (hook: (options: Page.BackPressOption) => any, target?: ComponentInternalInstance | null) => void;
export declare const onCopyUrl: (hook: (options: Page.OnCopyUrlOptions) => Page.CopyUrlContent, target?: ComponentInternalInstance | null) => void;
export declare const onError: (hook: (error: string) => void, target?: ComponentInternalInstance | null) => void;
export declare const onExit: (hook: () => void, target?: ComponentInternalInstance | null) => void;
export declare const onHide: (hook: () => any, target?: ComponentInternalInstance | null) => void;
export declare const onInit: (hook: (query?: AnyObject | undefined) => void, target?: ComponentInternalInstance | null) => void;
export declare const onLastPageBackPress: (hook: () => void, target?: ComponentInternalInstance | null) => void;
export declare const onLaunch: (hook: (options?: App.LaunchShowOption | undefined) => void, target?: ComponentInternalInstance | null) => void;
export declare const onLiveMount: (hook: (options: Page.LiveMountOptions) => Page.LiveMountContent | Promise<Page.LiveMountContent>, target?: ComponentInternalInstance | null) => void;
export declare const onLoad: (hook: (query?: AnyObject | undefined) => void, target?: ComponentInternalInstance | null) => void;
export declare const onNavigationBarButtonTap: (hook: (options: Page.NavigationBarButtonTapOption) => void, target?: ComponentInternalInstance | null) => void;
export declare const onNavigationBarSearchInputChanged: (hook: (event: Page.NavigationBarSearchInputEvent) => void, target?: ComponentInternalInstance | null) => void;
export declare const onNavigationBarSearchInputClicked: (hook: () => any, target?: ComponentInternalInstance | null) => void;
export declare const onNavigationBarSearchInputConfirmed: (hook: (event: Page.NavigationBarSearchInputEvent) => void, target?: ComponentInternalInstance | null) => void;
export declare const onNavigationBarSearchInputFocusChanged: (hook: onNavigationBarSearchInputFocusChangedHook, target?: ComponentInternalInstance | null) => void;
declare type onNavigationBarSearchInputFocusChangedHook = (options: NavigationBarSearchInputFocusChanged) => void;
export declare const onPageHide: (hook: () => any, target?: ComponentInternalInstance | null) => void;
export declare const onPageNotFound: (hook: (options: App.PageNotFoundOption) => void, target?: ComponentInternalInstance | null) => void;
export declare const onPageScroll: (hook: (options: Page.PageScrollOption) => void, target?: ComponentInternalInstance | null) => void;
export declare const onPageShow: (hook: () => void, target?: ComponentInternalInstance | null) => void;
export declare const onPullDownRefresh: (hook: () => any, target?: ComponentInternalInstance | null) => void;
export declare const onReachBottom: (hook: () => any, target?: ComponentInternalInstance | null) => void;
export declare const onReady: (hook: () => any, target?: ComponentInternalInstance | null) => void;
export declare const onResize: (hook: (options: Page.ResizeOption) => void, target?: ComponentInternalInstance | null) => void;
export declare const onSaveExitState: (hook: onSaveExitStateHook, target?: ComponentInternalInstance | null) => void;
declare type onSaveExitStateHook = () => SaveExitState;
export declare const onShareAppMessage: (hook: (options: Page.ShareAppMessageOption) => Page.CustomShareContent | Promise<Omit<Page.CustomShareContent, "promise">>, target?: ComponentInternalInstance | null) => void;
export declare const onShareChat: (hook: (options: Page.OnShareChatOptions) => Page.ShareChatContent, target?: ComponentInternalInstance | null) => void;
export declare const onShareTimeline: (hook: (options: Page.OnShareTimelineOptions) => Page.ShareTimelineContent, target?: ComponentInternalInstance | null) => void;
export declare const onShow: (hook: () => void, target?: ComponentInternalInstance | null) => void;
export declare const onTabItemTap: (hook: (options: Page.TabItemTapOption) => void, target?: ComponentInternalInstance | null) => void;
export declare const onThemeChange: (hook: (options: UniApp.OnThemeChangeCallbackResult) => void, target?: ComponentInternalInstance | null) => void;
export declare const onTitleClick: (hook: () => void, target?: ComponentInternalInstance | null) => void;
export declare const onUnhandledRejection: (hook: (options: UniApp.OnUnhandledRejectionCallbackResult) => void, target?: ComponentInternalInstance | null) => void;
export declare const onUnload: (hook: () => any, target?: ComponentInternalInstance | null) => void;
export declare const onUploadDouyinVideo: (hook: (options: Page.UploadDouyinVideoOptions) => Page.UploadDouyinVideoContent | Promise<Page.UploadDouyinVideoContent>, target?: ComponentInternalInstance | null) => void;
export declare function renderComponentSlot(slots: Slots, name: string, props?: any | null): any | null;
export declare function requireNativePlugin(name: string): any;
export declare function resolveEasycom(component: unknown, easycom: unknown): unknown;
declare interface SaveExitState {
data: any;
expireTimeStamp: number;
}
export declare const shallowSsrRef: SSRRef;
declare type SSRRef = (value: unknown, key?: string, shallow?: boolean) => ReturnType<typeof ref> | ReturnType<typeof shallowRef>;
export declare const ssrRef: SSRRef;
export { }
+140
View File
@@ -0,0 +1,140 @@
import { shallowRef, ref, getCurrentInstance, isInSSRComponentSetup, injectHook } from 'vue';
import { hasOwn } from '@vue/shared';
export { capitalize, extend, hasOwn, isPlainObject } from '@vue/shared';
import { sanitise, UNI_SSR_DATA, UNI_SSR_GLOBAL_DATA, UNI_SSR, ON_SHOW, ON_HIDE, ON_LAUNCH, ON_ERROR, ON_THEME_CHANGE, ON_PAGE_NOT_FOUND, ON_UNHANDLE_REJECTION, ON_LAST_PAGE_BACK_PRESS, ON_EXIT, ON_INIT, ON_LOAD, ON_READY, ON_UNLOAD, ON_RESIZE, ON_BACK_PRESS, ON_PAGE_SCROLL, ON_TAB_ITEM_TAP, ON_REACH_BOTTOM, ON_PULL_DOWN_REFRESH, ON_SAVE_EXIT_STATE, ON_TITLE_CLICK, ON_SHARE_TIMELINE, ON_SHARE_CHAT, ON_ADD_TO_FAVORITES, ON_SHARE_APP_MESSAGE, ON_COPY_URL, ON_UPLOAD_DOUYIN_VIDEO, ON_LIVE_MOUNT, ON_NAVIGATION_BAR_BUTTON_TAP, ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED, ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED, ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED, ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED } from '@dcloudio/uni-shared';
function getSSRDataType() {
return getCurrentInstance() ? UNI_SSR_DATA : UNI_SSR_GLOBAL_DATA;
}
function assertKey(key, shallow = false) {
if (!key) {
throw new Error(`${shallow ? 'shallowSsrRef' : 'ssrRef'}: You must provide a key.`);
}
}
const ssrClientRef = (value, key, shallow = false) => {
const valRef = shallow ? shallowRef(value) : ref(value);
// 非 h5 平台
if (typeof window === 'undefined') {
return valRef;
}
const __uniSSR = window[UNI_SSR];
if (!__uniSSR) {
return valRef;
}
const type = getSSRDataType();
assertKey(key, shallow);
if (hasOwn(__uniSSR[type], key)) {
valRef.value = __uniSSR[type][key];
if (type === UNI_SSR_DATA) {
delete __uniSSR[type][key]; // TODO 非全局数据仅使用一次?否则下次还会再次使用该数据
}
}
return valRef;
};
const globalData = {};
const ssrRef = (value, key) => {
return ssrClientRef(value, key);
};
const shallowSsrRef = (value, key) => {
return ssrClientRef(value, key, true);
};
function getSsrGlobalData() {
return sanitise(globalData);
}
/**
* uni 对象是跨实例的,而此处列的 API 均是需要跟当前实例关联的,比如 requireNativePlugin 获取 dom 时,依赖当前 weex 实例
*/
function getCurrentSubNVue() {
return uni.getSubNVueById(plus.webview.currentWebview().id);
}
function requireNativePlugin(name) {
return weex.requireModule(name);
}
function formatAppLog(type, filename, ...args) {
// @ts-expect-error
if (uni.__log__) {
// @ts-expect-error
uni.__log__(type, filename, ...args);
}
else {
console[type].apply(console, [...args, filename]);
}
}
function formatLog(type, filename, ...args) {
if (filename) {
args.push(filename);
}
console[type].apply(console, args);
}
function resolveEasycom(component, easycom) {
return typeof component === 'string' ? easycom : component;
}
/// <reference types="@dcloudio/types" />
// function isUniPage(target: ComponentInternalInstance | null): boolean {
// if (target && 'renderer' in target) {
// return target.renderer === 'page'
// }
// return true
// }
const createLifeCycleHook = (lifecycle, flag = 0 /* HookFlags.UNKNOWN */) => (hook, target = getCurrentInstance()) => {
if (isInSSRComponentSetup)
return;
// post-create lifecycle registrations are noops during SSR
injectHook(lifecycle, hook, target);
};
const onAppShow = /*#__PURE__*/ createLifeCycleHook(ON_SHOW, 1 /* HookFlags.APP */);
const onAppHide = /*#__PURE__*/ createLifeCycleHook(ON_HIDE, 1 /* HookFlags.APP */);
const onShow = /*#__PURE__*/ createLifeCycleHook(ON_SHOW, 2 /* HookFlags.PAGE */);
const onHide = /*#__PURE__*/ createLifeCycleHook(ON_HIDE, 2 /* HookFlags.PAGE */);
const onLaunch = /*#__PURE__*/ createLifeCycleHook(ON_LAUNCH, 1 /* HookFlags.APP */);
const onError = /*#__PURE__*/ createLifeCycleHook(ON_ERROR, 1 /* HookFlags.APP */);
const onThemeChange = /*#__PURE__*/ createLifeCycleHook(ON_THEME_CHANGE, 1 /* HookFlags.APP */);
const onPageNotFound = /*#__PURE__*/ createLifeCycleHook(ON_PAGE_NOT_FOUND, 1 /* HookFlags.APP */);
const onUnhandledRejection = /*#__PURE__*/ createLifeCycleHook(ON_UNHANDLE_REJECTION, 1 /* HookFlags.APP */);
const onLastPageBackPress = /*#__PURE__*/ createLifeCycleHook(ON_LAST_PAGE_BACK_PRESS, 1 /* HookFlags.APP */);
const onExit = /*#__PURE__*/ createLifeCycleHook(ON_EXIT, 1 /* HookFlags.APP */);
const onInit = /*#__PURE__*/ createLifeCycleHook(ON_INIT, 2 /* HookFlags.PAGE */ | 4 /* HookFlags.COMPONENT */);
// 小程序如果想在 setup 的 props 传递页面参数,需要定义 props,故同时暴露 onLoad 吧
const onLoad = /*#__PURE__*/ createLifeCycleHook(ON_LOAD, 2 /* HookFlags.PAGE */);
const onReady = /*#__PURE__*/ createLifeCycleHook(ON_READY, 2 /* HookFlags.PAGE */);
const onUnload = /*#__PURE__*/ createLifeCycleHook(ON_UNLOAD, 2 /* HookFlags.PAGE */);
const onResize = /*#__PURE__*/ createLifeCycleHook(ON_RESIZE, 2 /* HookFlags.PAGE */);
const onBackPress = /*#__PURE__*/ createLifeCycleHook(ON_BACK_PRESS, 2 /* HookFlags.PAGE */);
const onPageScroll = /*#__PURE__*/ createLifeCycleHook(ON_PAGE_SCROLL, 2 /* HookFlags.PAGE */);
const onTabItemTap = /*#__PURE__*/ createLifeCycleHook(ON_TAB_ITEM_TAP, 2 /* HookFlags.PAGE */);
const onReachBottom = /*#__PURE__*/ createLifeCycleHook(ON_REACH_BOTTOM, 2 /* HookFlags.PAGE */);
const onPullDownRefresh = /*#__PURE__*/ createLifeCycleHook(ON_PULL_DOWN_REFRESH, 2 /* HookFlags.PAGE */);
const onSaveExitState =
/*#__PURE__*/ createLifeCycleHook(ON_SAVE_EXIT_STATE, 2 /* HookFlags.PAGE */);
const onTitleClick = /*#__PURE__*/ createLifeCycleHook(ON_TITLE_CLICK, 2 /* HookFlags.PAGE */);
const onShareTimeline = /*#__PURE__*/ createLifeCycleHook(ON_SHARE_TIMELINE, 2 /* HookFlags.PAGE */);
const onShareChat = /*#__PURE__*/ createLifeCycleHook(ON_SHARE_CHAT, 2 /* HookFlags.PAGE */);
const onAddToFavorites = /*#__PURE__*/ createLifeCycleHook(ON_ADD_TO_FAVORITES, 2 /* HookFlags.PAGE */);
const onShareAppMessage = /*#__PURE__*/ createLifeCycleHook(ON_SHARE_APP_MESSAGE, 2 /* HookFlags.PAGE */);
const onCopyUrl = /*#__PURE__*/ createLifeCycleHook(ON_COPY_URL, 2 /* HookFlags.PAGE */);
const onUploadDouyinVideo = /*#__PURE__*/ createLifeCycleHook(ON_UPLOAD_DOUYIN_VIDEO, 2 /* HookFlags.PAGE */);
const onLiveMount = /*#__PURE__*/ createLifeCycleHook(ON_LIVE_MOUNT, 2 /* HookFlags.PAGE */);
const onNavigationBarButtonTap = /*#__PURE__*/ createLifeCycleHook(ON_NAVIGATION_BAR_BUTTON_TAP, 2 /* HookFlags.PAGE */);
const onNavigationBarSearchInputChanged =
/*#__PURE__*/ createLifeCycleHook(ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED, 2 /* HookFlags.PAGE */);
const onNavigationBarSearchInputClicked =
/*#__PURE__*/ createLifeCycleHook(ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED, 2 /* HookFlags.PAGE */);
const onNavigationBarSearchInputConfirmed =
/*#__PURE__*/ createLifeCycleHook(ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED, 2 /* HookFlags.PAGE */);
const onNavigationBarSearchInputFocusChanged =
/*#__PURE__*/ createLifeCycleHook(ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED, 2 /* HookFlags.PAGE */);
const onPageShow = onShow;
const onPageHide = onHide;
function renderComponentSlot(slots, name, props = null) {
if (slots[name]) {
return slots[name](props);
}
return null;
}
export { formatAppLog, formatLog, getCurrentSubNVue, getSsrGlobalData, onAddToFavorites, onAppHide, onAppShow, onBackPress, onCopyUrl, onError, onExit, onHide, onInit, onLastPageBackPress, onLaunch, onLiveMount, onLoad, onNavigationBarButtonTap, onNavigationBarSearchInputChanged, onNavigationBarSearchInputClicked, onNavigationBarSearchInputConfirmed, onNavigationBarSearchInputFocusChanged, onPageHide, onPageNotFound, onPageScroll, onPageShow, onPullDownRefresh, onReachBottom, onReady, onResize, onSaveExitState, onShareAppMessage, onShareChat, onShareTimeline, onShow, onTabItemTap, onThemeChange, onTitleClick, onUnhandledRejection, onUnload, onUploadDouyinVideo, renderComponentSlot, requireNativePlugin, resolveEasycom, shallowSsrRef, ssrRef };
+14
View File
@@ -0,0 +1,14 @@
'use strict';
var index = () => [
/* eslint-disable no-restricted-globals */
...require('@dcloudio/uni-cloud/lib/uni.plugin.js').default(),
/* eslint-disable no-restricted-globals */
...require('@dcloudio/uni-push/lib/uni.plugin.js')(),
/* eslint-disable no-restricted-globals */
...require('@dcloudio/uni-stat/lib/uni.plugin.js')(),
/* eslint-disable no-restricted-globals */
...require('@dcloudio/uni-console/lib/uni.plugin.js')(),
];
module.exports = index;
+1
View File
@@ -0,0 +1 @@
[https://dcloud.io/license/uni-app.html](https://dcloud.io/license/uni-app.html)
+43
View File
@@ -0,0 +1,43 @@
{
"name": "@dcloudio/uni-app",
"version": "3.0.0-alpha-5030620261112001",
"description": "@dcloudio/uni-app",
"main": "./dist/uni-app.cjs.js",
"module": "./dist/uni-app.es.js",
"types": "./dist/uni-app.d.ts",
"files": [
"dist",
"dist-x"
],
"sideEffects": false,
"repository": {
"type": "git",
"url": "git+https://github.com/dcloudio/uni-app.git",
"directory": "packages/uni-app"
},
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/dcloudio/uni-app/issues"
},
"gitHead": "33e807d66e1fe47e2ee08ad9c59247e37b8884da",
"uni-app": {
"name": "uni-app",
"main": "dist/uni.compiler.js"
},
"dependencies": {
"@vue/shared": "3.4.21",
"@dcloudio/uni-cloud": "3.0.0-alpha-5030620261112001",
"@dcloudio/uni-i18n": "3.0.0-alpha-5030620261112001",
"@dcloudio/uni-push": "3.0.0-alpha-5030620261112001",
"@dcloudio/uni-shared": "3.0.0-alpha-5030620261112001",
"@dcloudio/uni-stat": "3.0.0-alpha-5030620261112001",
"@dcloudio/uni-console": "3.0.0-alpha-5030620261112001",
"@dcloudio/uni-components": "3.0.0-alpha-5030620261112001"
},
"devDependencies": {
"@dcloudio/uni-uts-v1": "3.0.0-alpha-5030620261112001"
},
"peerDependencies": {
"@dcloudio/types": "3.4.31"
}
}
+202
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.
@@ -0,0 +1 @@
"use strict";var t=require("./index.js");const n="__UNI_AUTOMATOR_SOCKET_RETRY_RUNNER_WARNED__",e="__UNI_AUTOMATOR_SOCKET_RETRY_STATE__";const s=new t.Automator;let o,r=!1;try{o=require("jest-environment-node")}catch(t){o=require(require.resolve("jest-environment-node",{paths:[process.cwd()]}))}o&&o.TestEnvironment&&(r=!0,o=o.TestEnvironment);module.exports=class extends o{constructor(t,n){var e,s,o,i;super(r?{projectConfig:t}:t,n),process.env.UNI_AUTOMATOR_CONFIG?this.launchOptions=require(process.env.UNI_AUTOMATOR_CONFIG):this.launchOptions=t.testEnvironmentOptions?t.testEnvironmentOptions:t.projectConfig.testEnvironmentOptions,this.runner=t.runner||(null===(e=t.projectConfig)||void 0===e?void 0:e.runner),(null===(s=this.launchOptions)||void 0===s?void 0:s.web)&&Object.assign(this.launchOptions,{h5:this.launchOptions.web}),(null===(o=this.launchOptions)||void 0===o?void 0:o.app)&&Object.assign(this.launchOptions,{"app-plus":this.launchOptions.app});const a=(null===(i=this.launchOptions)||void 0===i?void 0:i.platform)||process.env.UNI_PLATFORM;("web"===a||"h5"===a||(null==a?void 0:a.startsWith("mp-")))&&(delete process.env.UNI_APP_X_DOM2,delete this.global.process.env.UNI_APP_X_DOM2)}async setup(){var o;await super.setup();const r=global;if("true"!==process.env.UNI_AUTOMATOR_RETRY_ON_SOCKET_CLOSE||r[n]||String(this.runner||"").includes("runner.js")||(r[n]=!0,console.warn("[uni-automator] socket retry requires Jest runner: @dcloudio/uni-automator/dist/runner.js")),r.__init__){if(!r.program)throw Error("Program init failed");this.launchOptions.platform.startsWith("app")&&process.env.UNI_AUTOMATOR_NEED_RESTART_BETWEEN_TEST&&(global.socketConnected=!1,await r.program.start("jest"),await new Promise((t=>{const n=setInterval((()=>{global.socketConnected&&(clearInterval(n),t(!0))}),500)})))}else r.__init__=!0,this.launchOptions.platform=this.launchOptions.platform||process.env.UNI_PLATFORM,r.program=await s.launch(this.launchOptions),(null===(o=this.launchOptions[this.launchOptions.platform])||void 0===o?void 0:o.remote)&&await r.program.remote(!0);this.global.program=r.program,this.global.uni=t.initUni(r.program),this.global[e]=r[e]}async teardown(){await super.teardown()}};
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
"use strict";module.exports=async function(){const t=global.program;if(!t||"function"!=typeof t.teardown)return;let o;const e=new Promise((t=>{o=setTimeout((()=>{console.warn("[uni-automator] program teardown timed out after 10000ms"),t()}),1e4)}));try{await Promise.race([t.teardown(),e])}finally{clearTimeout(o)}};
@@ -0,0 +1,33 @@
<script setup>
let firstBackTime = 0
onLaunch(() => {
console.log('App Launch')
})
onAppShow(() => {
console.log('App Show')
})
onAppHide(() => {
console.log('App Hide')
})
// #ifdef APP-ANDROID
onLastPageBackPress(() => {
console.log('App LastPageBackPress')
if (firstBackTime == 0) {
uni.showToast({
title: '再按一次退出应用',
position: 'bottom',
})
firstBackTime = Date.now()
setTimeout(() => {
firstBackTime = 0
}, 2000)
} else if (Date.now() - firstBackTime < 2000) {
firstBackTime = Date.now()
uni.exit()
}
})
// #endif
onExit(() => {
console.log('App Exit')
})
</script>
@@ -0,0 +1,9 @@
import App from './App.uvue'
import { createSSRApp } from 'vue'
export function createApp() {
const app = createSSRApp(App)
return {
app
}
}
@@ -0,0 +1,11 @@
{
"name" : "NAME",
"appid" : "APPID",
"description" : "",
"versionName" : "1.0.0",
"versionCode" : "100",
"uni-app-x" : {},
"app" : {
"defaultAppTheme": "auto"
}
}
@@ -0,0 +1,14 @@
{
"pages": [
{
"path": "pages/index/index",
"style": {
"navigationBarTitleText": "uni-app x"
}
}
],
"globalStyle": {
"navigationStyle": "custom",
"pageOrientation": "auto"
}
}
@@ -0,0 +1,120 @@
<template>
<web-view
ref="webviewElement"
id="webview"
style="flex: 1;"
:webview-styles="webviewStyles"
<!-- #ifdef APP-ANDROID -->
android-layer-type="software"
@load="onWebviewLoad"
<!-- #endif -->
:src="src"
@message="message"
@error="error"
/>
</template>
<script setup lang='uts'>
// #ifdef APP-IOS || APP-ANDROID
import { applyWebViewSnapshotTextMetricsPatch } from '@/tools/webview-snapshot-text-metrics.uts'
// #endif
// #ifdef APP-ANDROID
import { applyAndroidWebViewSafeArea } from '@/tools/android-webview-safe-area.uts'
// #endif
const instance = getCurrentInstance()!.proxy!
const src = ref(process.env.UNI_AUTOMATOR_APP_WEBVIEW_SRC)
const webviewElement = ref<UniWebViewElement | null>(null)
const webviewContext = ref<WebViewContext | null>(null)
const webviewStyles = ref({
progress: false
})
const safeAreaTop = ref(0)
// #ifdef APP-ANDROID
const onWebviewLoad = () => {
applyAndroidWebViewSafeArea(webviewContext.value)
}
onPageShow(() => {
UniWebViewElement.enableWholeDraw()
})
// #endif
onReady(() => {
const windowInfo = uni.getWindowInfo()
safeAreaTop.value = windowInfo.safeAreaInsets.top
webviewContext.value = uni.createWebViewContext('webview')
})
const initAutomator = () => {
const options = {
wsEndpoint: process.env.UNI_AUTOMATOR_WS_ENDPOINT
}
webviewContext.value!.evalJS(`initRuntimeAutomator(${JSON.stringify(options)})`)
// #ifdef APP-IOS || APP-ANDROID
applyWebViewSnapshotTextMetricsPatch(webviewContext.value)
// #endif
console.log('initRuntimeAutomator...')
}
const callback = (id : number, res : any | null, error : string) => {
webviewContext.value!.evalJS(`onPostMessageFromUniXWebView(${id},${JSON.stringify(res)},${JSON.stringify(error)})`)
}
const message = (msg: UniWebViewMessageEvent) => {
// #ifdef APP
const data = msg.detail.data[0];
const id = data["id"] as number
const type = data["type"] as string
const dataObj = data["data"] as UTSJSONObject
const action = dataObj["action"]!
const args = dataObj["args"]
// #endif
// #ifdef WEB || MP
const data = msg.detail.data.length ? msg.detail.data[0].data : msg.detail.data
const id = data["id"] as number
const type = data["type"] as string
const dataObj = data["data"]
const action = dataObj["action"]!
const args = dataObj["args"]
// #endif
if (type != 'automator') {
return;
}
if (action == 'ready') {
initAutomator()
} else {
console.log(id, action, args)
if (action == 'captureScreenshot') {
// 调用截图
(instance as Page).$viewToTempFilePath({
id: 'webview',
offsetY: `${safeAreaTop.value + 44}`,
overwrite: true,
wholeContent: true,
success: (res) => {
const fileManager = uni.getFileSystemManager()
fileManager.readFile({
encoding: 'base64',
filePath: res.tempFilePath,
success: (readFileRes) => {
callback(id, { data: readFileRes.data }, '')
},
fail: (error) => {
callback(id, '', error.errMsg)
},
} as ReadFileOptions)
},
fail: (res) => {
callback(id, '', res.errMsg)
}
})
}
}
}
const error = (event : WebViewErrorEvent) => {
console.log('webview load error', JSON.stringify(event.detail));
}
</script>
@@ -0,0 +1,110 @@
function getAndroidStatusBarHeight(): number {
const windowInfo = uni.getWindowInfo()
return windowInfo.statusBarHeight
}
function createStatusBarPlaceholderScript(height: number): string {
return `
(function(){
var height=${height};
var id='uni-app-x-android-pad-statusbar-placeholder';
var maxAttempts=60;
var attempts=0;
var observer=null;
var observedBody=null;
function shouldInsert(){
var pageHead=document.querySelector('.uni-page-head');
if(!pageHead){
// navigationStyle: "custom" does not render a uni-page-head.
return true;
}
if(!pageHead.getBoundingClientRect){
return false;
}
// Pixel XL pageHead 高度为 44.000xxx,故判断小于45
return pageHead.getBoundingClientRect().height<45;
}
function apply(){
if(height<=0||document.body==null){
return false;
}
var body=document.body;
var spacer=document.getElementById(id);
if(!shouldInsert()){
if(spacer!=null&&spacer.parentNode!=null){
spacer.parentNode.removeChild(spacer);
}
return false;
}
if(spacer==null){
spacer=document.createElement('div');
spacer.id=id;
spacer.setAttribute('aria-hidden','true');
}
spacer.style.height=height+'px';
spacer.style.minHeight=height+'px';
spacer.style.width='100%';
spacer.style.display='block';
spacer.style.flexShrink='0';
spacer.style.pointerEvents='none';
spacer.style.background='transparent';
if(body.firstChild!==spacer){
body.insertBefore(spacer,body.firstChild);
}
return true;
}
function observeBody(){
if(document.body==null||typeof MutationObserver!='function'){
return;
}
if(observedBody===document.body){
return;
}
if(observer!=null){
observer.disconnect();
}
observedBody=document.body;
observer=new MutationObserver(function(){
var body=document.body;
var spacer=document.getElementById(id);
if(body==null||spacer==null||spacer.parentNode!==body||body.firstChild!==spacer){
apply();
}
});
observer.observe(observedBody,{childList:true});
}
function retry(){
apply();
observeBody();
attempts+=1;
if(attempts<maxAttempts){
setTimeout(retry,100);
}
}
if(document.readyState=='loading'){
document.addEventListener('DOMContentLoaded',retry);
}
setTimeout(retry,0);
})();
`
}
export function insertStatusBarPlaceholder(webview: WebViewContext | null): void {
if (webview == null) return
const webviewContext = webview as WebViewContext
const statusBarHeight = getAndroidStatusBarHeight()
const script = createStatusBarPlaceholderScript(statusBarHeight)
webviewContext.evalJS(script)
}
@@ -0,0 +1,121 @@
function createAndroidWebViewSafeAreaScript(
height: number,
safeAreaInsetBottom: number
): string {
return `
(function(){
var height=${height};
var safeAreaInsetBottom=${safeAreaInsetBottom};
var safeAreaProperty='--uni-safe-area-inset-bottom';
var safeAreaValue=safeAreaInsetBottom+'px';
var id='uni-app-x-android-pad-statusbar-placeholder';
var maxAttempts=60;
var attempts=0;
var observer=null;
var observedBody=null;
function shouldInsert(){
var pageHead=document.querySelector('.uni-page-head');
if(!pageHead){
// navigationStyle: "custom" does not render a uni-page-head.
return true;
}
if(!pageHead.getBoundingClientRect){
return false;
}
// Pixel XL pageHead 高度为 44.000xxx,故判断小于45
return pageHead.getBoundingClientRect().height<45;
}
function apply(){
if(document.body==null){
return false;
}
var body=document.body;
var spacer=document.getElementById(id);
if(body.style.getPropertyValue(safeAreaProperty)!==safeAreaValue){
body.style.setProperty(safeAreaProperty,safeAreaValue);
}
if(height<=0){
return true;
}
if(!shouldInsert()){
if(spacer!=null&&spacer.parentNode!=null){
spacer.parentNode.removeChild(spacer);
}
return false;
}
if(spacer==null){
spacer=document.createElement('div');
spacer.id=id;
spacer.setAttribute('aria-hidden','true');
}
spacer.style.height=height+'px';
spacer.style.minHeight=height+'px';
spacer.style.width='100%';
spacer.style.display='block';
spacer.style.flexShrink='0';
spacer.style.pointerEvents='none';
spacer.style.background='transparent';
if(body.firstChild!==spacer){
body.insertBefore(spacer,body.firstChild);
}
return true;
}
function observeBody(){
if(document.body==null||typeof MutationObserver!='function'){
return;
}
if(observedBody===document.body){
return;
}
if(observer!=null){
observer.disconnect();
}
observedBody=document.body;
observer=new MutationObserver(function(){
var body=document.body;
var spacer=document.getElementById(id);
var safeAreaApplied=body!=null&&body.style.getPropertyValue(safeAreaProperty)===safeAreaValue;
if(!safeAreaApplied||spacer==null||spacer.parentNode!==body||body.firstChild!==spacer){
apply();
}
});
observer.observe(observedBody,{childList:true,attributes:true,attributeFilter:['style']});
}
function retry(){
apply();
observeBody();
attempts+=1;
if(attempts<maxAttempts){
setTimeout(retry,100);
}
}
if(document.readyState=='loading'){
document.addEventListener('DOMContentLoaded',retry);
}
setTimeout(retry,0);
})();
`
}
export function applyAndroidWebViewSafeArea(webview: WebViewContext | null): void {
if (webview == null) return
const webviewContext = webview as WebViewContext
const windowInfo = uni.getWindowInfo()
const script = createAndroidWebViewSafeAreaScript(
windowInfo.statusBarHeight,
windowInfo.safeAreaInsets.bottom
)
webviewContext.evalJS(script)
}
@@ -0,0 +1,184 @@
const buildIOSWebViewSnapshotTextMetricsScript = (): string => {
return `
(function () {
var styleId = '__uni_snapshot_ios_text_metrics_style__';
var scriptId = '__uni_snapshot_ios_text_metrics_script__';
var defaultLineHeight = '1.20';
if (window.__uniSnapshotIOSTextObserver) {
window.__uniSnapshotIOSTextObserver.disconnect();
window.__uniSnapshotIOSTextObserver = null;
}
window.__uniSnapshotTextNormalizeInstalled = false;
Array.prototype.forEach.call(document.querySelectorAll('style'), function(style) {
var text = style.textContent || '';
if (style.id == styleId ||
text.indexOf('uni-ios-snapshot-text-metrics') >= 0 ||
text.indexOf('__uniSnapshotIOSTextMetrics') >= 0 ||
text.indexOf('__uni_snapshot_multiline_text__') >= 0 ||
text.indexOf('__uniSnapshotTextNormalizeInstalled') >= 0 ||
text.indexOf('local(".SF UI Text")') >= 0 ||
text.indexOf('body { line-height: 1.35') >= 0 ||
text.indexOf('body { line-height: 1.20') >= 0) {
style.parentNode && style.parentNode.removeChild(style);
}
});
Array.prototype.forEach.call(document.querySelectorAll('script'), function(script) {
var text = script.textContent || '';
if (script.id == scriptId ||
text.indexOf('__uniSnapshotIOSTextMetrics') >= 0 ||
text.indexOf('__uniSnapshotIOSTextObserver') >= 0 ||
text.indexOf('__uniSnapshotTextNormalizeInstalled') >= 0) {
script.parentNode && script.parentNode.removeChild(script);
}
});
Array.prototype.forEach.call(document.querySelectorAll('[data-uni-ios-line-height-patched="1"]'), function(element) {
element.style.removeProperty('line-height');
element.removeAttribute('data-uni-ios-line-height-patched');
});
Array.prototype.forEach.call(document.querySelectorAll('.__uni_snapshot_multiline_text__'), function(element) {
element.style.removeProperty('line-height');
element.style.removeProperty('display');
element.classList.remove('__uni_snapshot_multiline_text__');
});
function selectorMatchesLineHeightRule(element, rule) {
if (!rule || !rule.selectorText || !rule.style) {
return false;
}
if (!rule.style.getPropertyValue('line-height')) {
return false;
}
try {
return element.matches(rule.selectorText);
} catch (_) {
return false;
}
}
function hasAuthoredLineHeightInRules(element, rules) {
if (!rules) {
return false;
}
for (var i = 0; i < rules.length; i++) {
var rule = rules[i];
if (selectorMatchesLineHeightRule(element, rule)) {
return true;
}
if (rule.cssRules && hasAuthoredLineHeightInRules(element, rule.cssRules)) {
return true;
}
}
return false;
}
function hasAuthoredLineHeightInStylesheet(element) {
var sheets = document.styleSheets;
for (var i = 0; i < sheets.length; i++) {
var rules = null;
try {
rules = sheets[i].cssRules;
} catch (_) {
continue;
}
if (hasAuthoredLineHeightInRules(element, rules)) {
return true;
}
}
return false;
}
function hasInlineLineHeight(element) {
return !!element &&
!!element.style &&
element.style.getPropertyValue('line-height') != '';
}
var bodyHasAuthoredLineHeight =
hasInlineLineHeight(document.body) ||
hasAuthoredLineHeightInStylesheet(document.body);
var styleLines = [
'/* uni-ios-snapshot-text-metrics */',
'html, body {',
' -webkit-text-size-adjust: 100%;',
' text-size-adjust: 100%;',
'}'
];
if (!bodyHasAuthoredLineHeight) {
styleLines.push(
'body {',
' line-height: ' + defaultLineHeight + ';',
'}'
);
}
var style = document.createElement('style');
style.id = styleId;
style.textContent = styleLines.join('\\n');
document.head.appendChild(style);
var script = document.createElement('script');
script.id = scriptId;
script.type = 'text/javascript';
script.textContent = 'window.__uniSnapshotIOSTextMetrics=' + JSON.stringify({
installed: true,
defaultLineHeight: defaultLineHeight,
bodyHasAuthoredLineHeight: bodyHasAuthoredLineHeight,
bodyPatched: !bodyHasAuthoredLineHeight,
scope: 'default-line-height-with-custom-preserved',
keepFontCSS: true,
keepLetterSpacing: true,
preserveExplicitTextStyle: true,
time: Date.now()
}) + ';';
document.head.appendChild(script);
})();
`
}
const buildAndroidWebViewSnapshotTextMetricsScript = (): string => {
return `
(function () {
const style = document.createElement('style');
style.textContent = '@font-face { font-family: "system"; src: local("Roboto"); ascent-override: 92%; descent-override: 8%; } body { font-family: "system"; line-height: 1.35; }';
document.head.appendChild(style);
const script = document.createElement('script');
script.type = 'text/javascript';
script.textContent = 'const observer = new MutationObserver((_) => { const elements = document.querySelectorAll("span"); elements.forEach(element => { const range = document.createRange(); range.selectNodeContents(element); const rects = range.getClientRects(); if (rects.length > 1 && (parseFloat(getComputedStyle(element.parentElement).getPropertyValue("line-height")) / parseFloat(getComputedStyle(element.parentElement).getPropertyValue("font-size")) == 1.35 || getComputedStyle(element.parentElement).getPropertyValue("line-height") == "")) {element.parentElement.style.setProperty("line-height", 1.215); }; }); });observer.observe(document.body, { childList: true, subtree: true, attributes: true });';
document.head.appendChild(script);
})();
`
}
const buildWebViewSnapshotTextMetricsScript = (): string => {
// #ifdef APP-IOS
return buildIOSWebViewSnapshotTextMetricsScript()
// #endif
// #ifdef APP-ANDROID
return buildAndroidWebViewSnapshotTextMetricsScript()
// #endif
}
export const applyWebViewSnapshotTextMetricsPatch = (context : WebViewContext | null): void => {
if (context !== null) {
context.evalJS(buildWebViewSnapshotTextMetricsScript())
}
}
+68
View File
@@ -0,0 +1,68 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_extra_1 = __importDefault(require("fs-extra"));
const path_1 = __importDefault(require("path"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
exports.default = [
(0, uni_cli_shared_1.defineUniMainJsPlugin)((opts) => {
return {
name: 'uni:automator',
enforce: 'pre',
configResolved() {
if (!process.env.UNI_AUTOMATOR_WS_ENDPOINT) {
return;
}
const pkg = JSON.parse(fs_extra_1.default.readFileSync(path_1.default.resolve(__dirname, '../package.json'), 'utf8'));
const automatorJson = JSON.stringify({
version: pkg.version,
wsEndpoint: process.env.UNI_AUTOMATOR_WS_ENDPOINT,
});
fs_extra_1.default.outputFileSync(path_1.default.resolve(process.env.UNI_OUTPUT_DIR, '../.automator/' + (0, uni_cli_shared_1.getPlatformDir)() + '/.automator.json'), automatorJson);
},
transform(code, id) {
if (!process.env.UNI_AUTOMATOR_WS_ENDPOINT) {
return null;
}
if (opts.filter(id)) {
const platform = process.env.UNI_PLATFORM;
// 仅 app-android
if ((platform === 'app' || platform === 'app-harmony') &&
process.env.UNI_APP_X === 'true') {
// app-webview,不增加 initAutomator
if (process.env.UNI_AUTOMATOR_APP_WEBVIEW === 'true') {
return null;
}
if (process.env.UNI_UTS_PLATFORM === 'app-android' &&
process.env.UNI_APP_X_DOM2 !== 'true') {
const automatorPath = (0, uni_cli_shared_1.normalizePath)((0, uni_cli_shared_1.resolveBuiltIn)(`@dcloudio/uni-app-uts/lib/automator/android/index.uts`));
return {
code:
// 增加个换行,避免最后是注释且无换行
code + `;\nimport { initAutomator } from '${automatorPath}';`,
map: null,
};
}
else if (process.env.UNI_UTS_PLATFORM === 'app-ios' ||
process.env.UNI_UTS_PLATFORM === 'app-harmony' ||
(process.env.UNI_UTS_PLATFORM === 'app-android' &&
process.env.UNI_APP_X_DOM2 === 'true')) {
const automatorPath = (0, uni_cli_shared_1.normalizePath)((0, uni_cli_shared_1.resolveBuiltIn)(`@dcloudio/uni-app-uts/lib/automator/ios/automator.js`));
return {
code: code + `;\nimport '${automatorPath}';`,
map: null,
};
}
}
const automatorPath = (0, uni_cli_shared_1.normalizePath)((0, uni_cli_shared_1.resolveBuiltIn)(`@dcloudio/uni-${platform === 'app' ? 'app-plus' : platform}/lib/automator.js`));
return {
code: code + `;\nimport '${automatorPath}';`,
map: null,
};
}
},
};
}),
];
+1
View File
@@ -0,0 +1 @@
[https://dcloud.io/license/uni-app.html](https://dcloud.io/license/uni-app.html)
+54
View File
@@ -0,0 +1,54 @@
{
"name": "@dcloudio/uni-automator",
"version": "3.0.0-alpha-5030620261112001",
"description": "@dcloudio/uni-automator",
"main": "dist/index.js",
"files": [
"dist",
"lib"
],
"sideEffects": false,
"repository": {
"type": "git",
"url": "git+https://github.com/dcloudio/uni-app.git",
"directory": "packages/uni-automator"
},
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/dcloudio/uni-app/issues"
},
"uni-app": {
"name": "uniAutomator",
"apply": [
"app",
"h5",
"mp-weixin",
"mp-alipay",
"app-harmony"
],
"uvue": true
},
"gitHead": "33e807d66e1fe47e2ee08ad9c59247e37b8884da",
"dependencies": {
"address": "^1.1.2",
"cross-env": "^7.0.3",
"debug": "4.3.7",
"default-gateway": "^6.0.3",
"fs-extra": "10.1.0",
"jsonc-parser": "3.3.1",
"licia": "1.41.1",
"merge": "2.1.1",
"qrcode-reader": "1.0.4",
"qrcode-terminal": "0.12.0",
"ws": "8.18.0",
"@dcloudio/uni-cli-shared": "3.0.0-alpha-5030620261112001"
},
"devDependencies": {
"@types/debug": "4.1.12",
"@types/fs-extra": "9.0.13"
},
"peerDependencies": {
"jest": "27.0.4",
"jest-environment-node": "27.5.1"
}
}
+202
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.
+1
View File
@@ -0,0 +1 @@
export {};
+4
View File
@@ -0,0 +1,4 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const alias_1 = require("./hbx/alias");
(0, alias_1.initModuleAlias)();
@@ -0,0 +1,3 @@
declare function checkUpdate1(options: any): Promise<undefined>;
export declare const checkUpdate: typeof checkUpdate1;
export {};
+61
View File
@@ -0,0 +1,61 @@
/* eslint-disable */
// @ts-ignore
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkUpdate = void 0;
var __importDefault = this && this.__importDefault || function (mod) { return mod && mod.__esModule ? mod : { default: mod }; };
Object.defineProperty(exports, "__esModule", { value: !0 }), exports.createPostData = exports.getMac = exports.md5 = exports.checkLocalCache = exports.checkUpdate1 = void 0;
const fs_extra_1 = __importDefault(require("fs-extra")), os_1 = __importDefault(require("os")), path_1 = __importDefault(require("path")), debug_1 = __importDefault(require("debug")), crypto_1 = __importDefault(require("crypto")), https_1 = require("https"), compare_versions_1 = __importDefault(require("compare-versions")), shared_1 = require("@vue/shared"), json_1 = require("./json"), hbx_1 = require("./hbx"), debugCheckUpdate = (0, debug_1.default)("uni:check-update"), INTERVAL = 864e5;
async function checkUpdate1(options) { if (process.env.CI)
return void debugCheckUpdate("isInCI"); if ((0, hbx_1.isInHBuilderX)())
return void debugCheckUpdate("isInHBuilderX"); const { inputDir: inputDir, compilerVersion: compilerVersion } = options, updateCache = readCheckUpdateCache(inputDir); debugCheckUpdate("read.cache", updateCache); const res = checkLocalCache(updateCache, compilerVersion); res ? (0, shared_1.isString)(res) && (console.log(), console.log(res)) : await checkVersion(options, normalizeUpdateCache(updateCache, (0, json_1.parseManifestJsonOnce)(inputDir))), writeCheckUpdateCache(inputDir, statUpdateCache(normalizeUpdateCache(updateCache))); }
function normalizeUpdateCache(updateCache, manifestJson) { const platform = process.env.UNI_PLATFORM; if (updateCache[platform] || (updateCache[platform] = { appid: "", dev: 0, build: 0 }), manifestJson) {
const platformOptions = manifestJson["app" === platform ? "app-plus" : platform];
updateCache[platform].appid = platformOptions && (platformOptions.appid || platformOptions.package) || "";
} return updateCache; }
function statUpdateCache(updateCache) { debugCheckUpdate("stat.before", updateCache); const platform = process.env.UNI_PLATFORM, type = "production" === process.env.NODE_ENV ? "build" : "dev", platformOptions = updateCache[platform]; return platformOptions[type] = (platformOptions[type] || 0) + 1, debugCheckUpdate("stat.after", updateCache), updateCache; }
function getFilepath(inputDir, filename) { return path_1.default.resolve(os_1.default.tmpdir(), "uni-app-cli", md5(inputDir), filename); }
function getCheckUpdateFilepath(inputDir) { return getFilepath(inputDir, "check-update.json"); }
function generateVid() { let result = ""; for (let i = 0; i < 4; i++)
result += (65536 * (1 + Math.random()) | 0).toString(16).substring(1); return "UNI_" + result.toUpperCase(); }
function createCheckUpdateCache(vid = generateVid()) { return { vid: generateVid(), lastCheck: 0 }; }
function readCheckUpdateCache(inputDir) { const updateFilepath = getCheckUpdateFilepath(inputDir); if (debugCheckUpdate("read:", updateFilepath), fs_extra_1.default.existsSync(updateFilepath))
try {
return require(updateFilepath);
}
catch (e) {
debugCheckUpdate("read.error", e);
} return createCheckUpdateCache(); }
function checkLocalCache(updateCache, compilerVersion, interval = INTERVAL) { return updateCache.lastCheck ? Date.now() - updateCache.lastCheck > interval ? (debugCheckUpdate("cache: lastCheck > interval"), !1) : !(updateCache.newVersion && (0, compare_versions_1.default)(updateCache.newVersion, compilerVersion) > 0) || (debugCheckUpdate("cache: find new version"), updateCache.note) : (debugCheckUpdate("cache: lastCheck not found"), !1); }
function writeCheckUpdateCache(inputDir, updateCache) { const filepath = getCheckUpdateFilepath(inputDir); debugCheckUpdate("write:", filepath, updateCache); try {
fs_extra_1.default.outputFileSync(filepath, JSON.stringify(updateCache));
}
catch (e) {
debugCheckUpdate("write.error", e);
} }
function md5(str) { return crypto_1.default.createHash("md5").update(str).digest("hex"); }
function getMac() { 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 || "00:00:00:00:00:00" !== item.mac)) {
if ((0, shared_1.isString)(item.family) && ("IPv4" === item.family || "IPv6" === item.family)) {
mac = item.mac;
break;
}
if ("number" == typeof item.family && (4 === item.family || 6 === item.family)) {
mac = item.mac;
break;
}
}
}
} return mac; }
function createPostData({ versionType: versionType, compilerVersion: compilerVersion }, manifestJson, updateCache) { const data = { vv: 3, device: md5(getMac()), vtype: versionType, vcode: compilerVersion }; return manifestJson.appid ? data.appid = manifestJson.appid : data.vid = updateCache.vid, Object.keys(updateCache).forEach((name => { const value = updateCache[name]; (0, shared_1.isPlainObject)(value) && ((0, shared_1.hasOwn)(value, "dev") || (0, shared_1.hasOwn)(value, "build")) && (data[name] = value); })), JSON.stringify(data); }
function handleCheckVersion({ code: code, isUpdate: isUpdate, newVersion: newVersion, note: note }, updateCache) { 0 === code && (Object.keys(updateCache).forEach((key => { "vid" !== key && delete updateCache[key]; })), updateCache.lastCheck = Date.now(), isUpdate ? (updateCache.note = note, updateCache.newVersion = newVersion) : (delete updateCache.note, delete updateCache.newVersion)); }
exports.checkUpdate1 = checkUpdate1, exports.checkLocalCache = checkLocalCache, exports.md5 = md5, exports.getMac = getMac, exports.createPostData = createPostData;
const HOSTNAME = "uniapp.dcloud.net.cn", PATH = "/update/cli";
function checkVersion(options, updateCache) { return new Promise((resolve => { const postData = JSON.stringify({ id: createPostData(options, (0, json_1.parseManifestJsonOnce)(options.inputDir), updateCache) }); let responseData = ""; const req = (0, https_1.request)({ hostname: HOSTNAME, path: PATH, port: 443, method: "POST", headers: { "Content-Type": "application/json", "Content-Length": postData.length } }, (res => { res.setEncoding("utf8"), res.on("data", (chunk => { responseData += chunk; })), res.on("end", (() => { debugCheckUpdate("response: ", responseData); try {
handleCheckVersion(JSON.parse(responseData), updateCache);
}
catch (e) { } resolve(!0); })), res.on("error", (e => { debugCheckUpdate("response.error:", e), resolve(!1); })); })).on("error", (e => { debugCheckUpdate("request.error:", e), resolve(!1); })); debugCheckUpdate("request: ", postData), req.write(postData), req.end(); })); }
exports.checkUpdate = checkUpdate1;
+43
View File
@@ -0,0 +1,43 @@
export declare const PUBLIC_DIR = "static";
export declare const EXTNAME_JS: string[];
export declare const EXTNAME_TS: string[];
export declare const EXTNAME_VUE: string[];
export declare const X_EXTNAME_VUE: string[];
export declare const EXTNAME_VUE_TEMPLATE: string[];
export declare const EXTNAME_VUE_RE: RegExp;
export declare const EXTNAME_JS_RE: RegExp;
export declare const EXTNAME_TS_RE: RegExp;
export declare const DEFAULT_APPID = "__UNI__uniappx";
export declare const SPECIAL_CHARS: {
WARN_BLOCK: string;
ERROR_BLOCK: string;
};
export declare const extensions: string[];
export declare const uni_app_x_extensions: string[];
export declare const PAGES_JSON_JS = "pages-json-js";
export declare const PAGES_JSON_UTS = "pages-json-uts";
export declare const MANIFEST_JSON_JS = "manifest-json-js";
export declare const MANIFEST_JSON_UTS = "manifest-json-uts";
export declare const JSON_JS_MAP: {
readonly 'pages.json': "pages-json-js";
readonly 'manifest.json': "manifest-json-js";
};
export declare const ASSETS_INLINE_LIMIT: number;
export declare const APP_SERVICE_FILENAME = "app-service.js";
export declare const APP_CONFIG = "app-config.js";
export declare const APP_CONFIG_SERVICE = "app-config-service.js";
export declare const BINDING_COMPONENTS = "__BINDING_COMPONENTS__";
export declare const PAGE_EXTNAME_APP: string[];
export declare const PAGE_EXTNAME: string[];
export declare const X_PAGE_EXTNAME: string[];
export declare const X_PAGE_EXTNAME_APP: string[];
export declare const H5_API_STYLE_PATH = "@dcloudio/uni-h5/style/api/";
export declare const H5_FRAMEWORK_STYLE_PATH = "@dcloudio/uni-h5/style/framework/";
export declare const H5_COMPONENTS_STYLE_PATH = "@dcloudio/uni-h5/style/";
export declare const BASE_COMPONENTS_STYLE_PATH = "@dcloudio/uni-components/style/";
export declare const X_BASE_COMPONENTS_STYLE_PATH = "@dcloudio/uni-components/style-x/";
export declare const X_VAPOR_BASE_COMPONENTS_STYLE_PATH = "@dcloudio/uni-components/style-x-vapor/";
export declare const COMMON_EXCLUDE: RegExp[];
export declare const KNOWN_ASSET_TYPES: string[];
export declare const DEFAULT_ASSETS_RE: RegExp;
export declare const TEXT_STYLE: string[];
+92
View File
@@ -0,0 +1,92 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TEXT_STYLE = exports.DEFAULT_ASSETS_RE = exports.KNOWN_ASSET_TYPES = exports.COMMON_EXCLUDE = exports.X_VAPOR_BASE_COMPONENTS_STYLE_PATH = exports.X_BASE_COMPONENTS_STYLE_PATH = exports.BASE_COMPONENTS_STYLE_PATH = exports.H5_COMPONENTS_STYLE_PATH = exports.H5_FRAMEWORK_STYLE_PATH = exports.H5_API_STYLE_PATH = exports.X_PAGE_EXTNAME_APP = exports.X_PAGE_EXTNAME = exports.PAGE_EXTNAME = exports.PAGE_EXTNAME_APP = exports.BINDING_COMPONENTS = exports.APP_CONFIG_SERVICE = exports.APP_CONFIG = exports.APP_SERVICE_FILENAME = exports.ASSETS_INLINE_LIMIT = exports.JSON_JS_MAP = exports.MANIFEST_JSON_UTS = exports.MANIFEST_JSON_JS = exports.PAGES_JSON_UTS = exports.PAGES_JSON_JS = exports.uni_app_x_extensions = exports.extensions = exports.SPECIAL_CHARS = exports.DEFAULT_APPID = exports.EXTNAME_TS_RE = exports.EXTNAME_JS_RE = exports.EXTNAME_VUE_RE = exports.EXTNAME_VUE_TEMPLATE = exports.X_EXTNAME_VUE = exports.EXTNAME_VUE = exports.EXTNAME_TS = exports.EXTNAME_JS = exports.PUBLIC_DIR = void 0;
exports.PUBLIC_DIR = 'static';
exports.EXTNAME_JS = ['.js', '.ts', '.jsx', '.tsx', '.uts'];
exports.EXTNAME_TS = ['.ts', '.tsx'];
exports.EXTNAME_VUE = ['.vue', '.nvue', '.uvue'];
exports.X_EXTNAME_VUE = ['.uvue', '.vue'];
exports.EXTNAME_VUE_TEMPLATE = ['.vue', '.nvue', '.uvue', '.jsx', '.tsx'];
exports.EXTNAME_VUE_RE = /\.(vue|nvue|uvue)$/;
exports.EXTNAME_JS_RE = /\.(js|jsx|ts|uts|tsx|mjs)$/;
exports.EXTNAME_TS_RE = /\.tsx?$/;
exports.DEFAULT_APPID = '__UNI__uniappx';
exports.SPECIAL_CHARS = {
WARN_BLOCK: '\uFEFF', // 警告块前后标识
ERROR_BLOCK: '\u2060', // 错误块前后标识
};
const COMMON_EXTENSIONS = [
'.uts',
'.mjs',
'.js',
'.ts',
'.jsx',
'.tsx',
'.json',
];
exports.extensions = COMMON_EXTENSIONS.concat(exports.EXTNAME_VUE);
exports.uni_app_x_extensions = COMMON_EXTENSIONS.concat(['.uvue', '.vue']);
exports.PAGES_JSON_JS = 'pages-json-js';
exports.PAGES_JSON_UTS = 'pages-json-uts';
exports.MANIFEST_JSON_JS = 'manifest-json-js';
exports.MANIFEST_JSON_UTS = 'manifest-json-uts';
exports.JSON_JS_MAP = {
'pages.json': exports.PAGES_JSON_JS,
'manifest.json': exports.MANIFEST_JSON_JS,
};
exports.ASSETS_INLINE_LIMIT = 40 * 1024;
exports.APP_SERVICE_FILENAME = 'app-service.js';
exports.APP_CONFIG = 'app-config.js';
exports.APP_CONFIG_SERVICE = 'app-config-service.js';
exports.BINDING_COMPONENTS = '__BINDING_COMPONENTS__';
// APP 平台解析页面后缀的优先级
exports.PAGE_EXTNAME_APP = ['.nvue', '.vue', '.tsx', '.jsx', '.js'];
// 其他平台解析页面后缀的优先级
exports.PAGE_EXTNAME = ['.vue', '.nvue', '.tsx', '.jsx', '.js'];
exports.X_PAGE_EXTNAME = ['.uvue', '.vue', '.tsx', '.jsx', '.js'];
exports.X_PAGE_EXTNAME_APP = ['.uvue', '.tsx', '.jsx', '.js'];
exports.H5_API_STYLE_PATH = '@dcloudio/uni-h5/style/api/';
exports.H5_FRAMEWORK_STYLE_PATH = '@dcloudio/uni-h5/style/framework/';
exports.H5_COMPONENTS_STYLE_PATH = '@dcloudio/uni-h5/style/';
exports.BASE_COMPONENTS_STYLE_PATH = '@dcloudio/uni-components/style/';
exports.X_BASE_COMPONENTS_STYLE_PATH = '@dcloudio/uni-components/style-x/';
exports.X_VAPOR_BASE_COMPONENTS_STYLE_PATH = '@dcloudio/uni-components/style-x-vapor/';
exports.COMMON_EXCLUDE = [
/\/pages\.json\.js$/,
/\/manifest\.json\.js$/,
/\/vite\//,
/\/@vue\//,
/\/vue-router\//,
/\/vuex\//,
/\/vue-i18n\//,
/\/@dcloudio\/uni-h5-vue/,
/\/@dcloudio\/uni-shared/,
];
exports.KNOWN_ASSET_TYPES = [
// images
'png',
'jpe?g',
'gif',
'svg',
'ico',
'webp',
'avif',
// media
'mp4',
'webm',
'ogg',
'mp3',
'wav',
'flac',
'aac',
// fonts
'woff2?',
'eot',
'ttf',
'otf',
// other
'pdf',
'txt',
];
exports.DEFAULT_ASSETS_RE = new RegExp(`\\.(` + exports.KNOWN_ASSET_TYPES.join('|') + `)(\\?.*)?$`);
exports.TEXT_STYLE = ['black', 'white'];
+24
View File
@@ -0,0 +1,24 @@
export declare function resolveWebVaporComponentStyle(name: string): string | undefined;
export declare const API_DEPS_CSS: (isX: boolean) => {
showModal: string[];
showToast: string[];
showActionSheet: string[];
previewImage: string[];
openLocation: string[];
chooseLocation: string[];
showLoading: string[];
};
export declare const COMPONENT_DEPS_CSS: (isX: boolean) => {
waterflow?: string[] | undefined;
canvas: string[];
image: string[];
'movable-area': string[];
'picker-view': string[];
'picker-view-column': string[];
'rich-text': string[];
textarea: string[];
'web-view': string[];
picker: string[];
'scroll-view': string[];
'list-view': string[];
};
+118
View File
@@ -0,0 +1,118 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.COMPONENT_DEPS_CSS = exports.API_DEPS_CSS = exports.resolveWebVaporComponentStyle = void 0;
const constants_1 = require("./constants");
const x_1 = require("./x");
const uni_shared_1 = require("@dcloudio/uni-shared");
const RESIZE_SENSOR_CSS = constants_1.BASE_COMPONENTS_STYLE_PATH + 'resize-sensor.css';
const REFRESHER_CSS = constants_1.BASE_COMPONENTS_STYLE_PATH + 'refresher.css';
const webVaporStyleComponents = new Set([
'input',
'textarea',
'scroll-view',
'video',
'web-view',
'ad',
]);
// Easycom、API 和框架内部组件共用同一份路径选择,避免漏载或同时加载旧版与 Vapor 样式。
// 同步组件优先:将来接入内网实现后,自动使用其生成样式。
function resolveWebVaporComponentStyle(name) {
if ((0, uni_shared_1.hasWebVaporComponentStyle)(name)) {
return constants_1.X_VAPOR_BASE_COMPONENTS_STYLE_PATH + name + '.css';
}
if (webVaporStyleComponents.has(name)) {
return constants_1.H5_COMPONENTS_STYLE_PATH + 'vapor/' + name + '.css';
}
}
exports.resolveWebVaporComponentStyle = resolveWebVaporComponentStyle;
function componentCss(name, isWebVapor) {
return ((isWebVapor && resolveWebVaporComponentStyle(name)) ||
constants_1.BASE_COMPONENTS_STYLE_PATH + name + '.css');
}
// 框架内部的 ScrollView 已在框架构建时编译,用户项目的 Easycom 不会再次扫描。
// Web Vapor 的外层组件或 API 需显式声明其样式,避免发行裁剪时漏载。
function webVaporScrollViewCss() {
return [componentCss('scroll-view', true)];
}
const API_DEPS_CSS = (isX) => {
// API 内部组件已随框架编译,需在项目使用该 API 时加载对应渲染模式的样式。
const isWebVapor = isX && (0, x_1.isUniAppXWebVapor)();
const scrollViewCss = isWebVapor ? webVaporScrollViewCss() : [];
const deps_css = {
showModal: [],
showToast: [`${constants_1.H5_API_STYLE_PATH}toast.css`],
showActionSheet: scrollViewCss,
previewImage: [
RESIZE_SENSOR_CSS,
componentCss('swiper', isWebVapor),
componentCss('swiper-item', isWebVapor),
`${constants_1.BASE_COMPONENTS_STYLE_PATH}movable-area.css`,
`${constants_1.BASE_COMPONENTS_STYLE_PATH}movable-view.css`,
],
openLocation: [`${constants_1.H5_API_STYLE_PATH}location-view.css`],
chooseLocation: [],
showLoading: [],
};
if (isX) {
deps_css.showModal = [
componentCss('textarea', isWebVapor),
...scrollViewCss,
];
deps_css.chooseLocation = [
`${constants_1.BASE_COMPONENTS_STYLE_PATH}/view.css`,
`${constants_1.BASE_COMPONENTS_STYLE_PATH}/text.css`,
isWebVapor
? componentCss('input', true)
: `${constants_1.BASE_COMPONENTS_STYLE_PATH}/input.css`,
`${constants_1.H5_COMPONENTS_STYLE_PATH}/map.css`,
...(isWebVapor
? scrollViewCss
: [`${constants_1.BASE_COMPONENTS_STYLE_PATH}/scroll-view.css`]),
`${constants_1.BASE_COMPONENTS_STYLE_PATH}/image.css`,
];
deps_css.showLoading = [
`${isWebVapor
? constants_1.X_VAPOR_BASE_COMPONENTS_STYLE_PATH
: constants_1.X_BASE_COMPONENTS_STYLE_PATH}loading.css`,
];
}
else {
deps_css.showModal = [`${constants_1.H5_API_STYLE_PATH}modal.css`];
deps_css.showActionSheet = [`${constants_1.H5_API_STYLE_PATH}action-sheet.css`];
deps_css.chooseLocation = [
`${constants_1.H5_API_STYLE_PATH}/location-picker.css`,
`${constants_1.BASE_COMPONENTS_STYLE_PATH}/input.css`,
`${constants_1.H5_COMPONENTS_STYLE_PATH}/map.css`,
`${constants_1.BASE_COMPONENTS_STYLE_PATH}/scroll-view.css`,
];
}
return deps_css;
};
exports.API_DEPS_CSS = API_DEPS_CSS;
const COMPONENT_DEPS_CSS = (isX) => {
const isWebVapor = isX && (0, x_1.isUniAppXWebVapor)();
const scrollViewCss = isWebVapor ? webVaporScrollViewCss() : [];
return {
canvas: [RESIZE_SENSOR_CSS],
image: [RESIZE_SENSOR_CSS],
'movable-area': [RESIZE_SENSOR_CSS],
'picker-view': [RESIZE_SENSOR_CSS],
'picker-view-column': [RESIZE_SENSOR_CSS, ...scrollViewCss],
'rich-text': [RESIZE_SENSOR_CSS],
textarea: [RESIZE_SENSOR_CSS],
'web-view': [RESIZE_SENSOR_CSS],
picker: [
RESIZE_SENSOR_CSS,
componentCss('picker-view', isWebVapor),
componentCss('picker-view-column', isWebVapor),
...scrollViewCss,
],
'scroll-view': isWebVapor ? [] : [REFRESHER_CSS],
'list-view': [
RESIZE_SENSOR_CSS,
...(isWebVapor ? scrollViewCss : [REFRESHER_CSS]),
],
...(isWebVapor ? { waterflow: [RESIZE_SENSOR_CSS, ...scrollViewCss] } : {}),
};
};
exports.COMPONENT_DEPS_CSS = COMPONENT_DEPS_CSS;
@@ -0,0 +1,4 @@
export declare const JS_STYLE_PLACEHOLDER_MARKER = "__js_style_placeholder__";
export declare function createJsStylePlaceholder(id: string): string;
export declare function createJsStylePlaceholderRegExp(id: string): RegExp;
export declare const ANY_JS_STYLE_PLACEHOLDER_RE: RegExp;
@@ -0,0 +1,21 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ANY_JS_STYLE_PLACEHOLDER_RE = exports.createJsStylePlaceholderRegExp = exports.createJsStylePlaceholder = exports.JS_STYLE_PLACEHOLDER_MARKER = void 0;
const hash_sum_1 = __importDefault(require("hash-sum"));
exports.JS_STYLE_PLACEHOLDER_MARKER = '__js_style_placeholder__';
function createJsStylePlaceholder(id) {
const hashId = (0, hash_sum_1.default)(id);
return JSON.stringify({
[exports.JS_STYLE_PLACEHOLDER_MARKER]: hashId,
});
}
exports.createJsStylePlaceholder = createJsStylePlaceholder;
function createJsStylePlaceholderRegExp(id) {
const hashId = (0, hash_sum_1.default)(id);
return new RegExp(`\\{\\s*(?:"${exports.JS_STYLE_PLACEHOLDER_MARKER}"|'${exports.JS_STYLE_PLACEHOLDER_MARKER}'|${exports.JS_STYLE_PLACEHOLDER_MARKER})\\s*:\\s*(?:"${hashId}"|'${hashId}')\\s*\\}`, 'g');
}
exports.createJsStylePlaceholderRegExp = createJsStylePlaceholderRegExp;
exports.ANY_JS_STYLE_PLACEHOLDER_RE = new RegExp(`\\{\\s*(?:"${exports.JS_STYLE_PLACEHOLDER_MARKER}"|'${exports.JS_STYLE_PLACEHOLDER_MARKER}'|${exports.JS_STYLE_PLACEHOLDER_MARKER})\\s*:\\s*(?:"[^"]+?"|'[^']+?')\\s*\\}`, 'g');
@@ -0,0 +1,5 @@
export * from './sharedData';
export * from './script';
export * from './vue';
export * from './fontFamily';
export * from './rootScrollView';
+21
View File
@@ -0,0 +1,21 @@
"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 __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./sharedData"), exports);
__exportStar(require("./script"), exports);
__exportStar(require("./vue"), exports);
__exportStar(require("./fontFamily"), exports);
__exportStar(require("./rootScrollView"), exports);
@@ -0,0 +1,47 @@
export interface VueCodePosition {
line: number;
column: number;
}
export interface VueCodeEditRange {
start: VueCodePosition;
end: VueCodePosition;
/**
* 调用方替换时建议只移除非换行字符,用于尽量保持错误定位和调试行号不变。
*/
preserveLineBreaks: true;
/**
* 开始范围包含首个子节点前的缩进,调用方需要保留这段缩进,避免改变子节点格式。
*/
preserveEndIndent?: true;
}
export type VueCodeEditRangesResult = Record<string, VueCodeEditRange[]>;
/**
* 批量定位由 `#ifdef APP` 包裹的根 scroll-view 需要移除的范围。
* 只返回需要修改的行列号,不修改文件,也不返回修改后的文件内容。
*/
export declare function resolveAppRootScrollViewEditRanges(vueFiles: string[], inputDir: string): VueCodeEditRangesResult;
/**
* 蒸汽模式下,页面根节点会自动补一个 scroll-view。
* 这里仅用正则做精确匹配:命中范围宁可保守,也不能误报。
*/
export declare function hasAppRootScrollViewWrappedByIfdef(code: string): boolean;
/**
* 仅在 dom2 页面整文件预处理时定位需要提示优化建议的根 scroll-view 节点。
*/
export declare function resolveDom2RootScrollViewWarnLocation(code: string, filename: string, isVueSubRequest: boolean): {
loc: import("@vue/compiler-core").SourceLocation | {
start: {
line: number;
column: number;
offset: number;
};
end: {
line: number;
column: number;
offset: number;
};
};
source: string;
} | undefined;
export declare function warnDom2RootScrollView(code: string, filename: string, isVueSubRequest: boolean): void;
export declare function resolveAppRootScrollViewEditRangesByCode(code: string, filename: string): VueCodeEditRange[];
@@ -0,0 +1,283 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveAppRootScrollViewEditRangesByCode = exports.warnDom2RootScrollView = exports.resolveDom2RootScrollViewWarnLocation = exports.hasAppRootScrollViewWrappedByIfdef = exports.resolveAppRootScrollViewEditRanges = void 0;
const fs_extra_1 = require("fs-extra");
const path_1 = require("path");
const compiler_sfc_1 = require("@vue/compiler-sfc");
const json_1 = require("../json");
const logs_1 = require("../logs");
const messages_1 = require("../messages");
const utils_1 = require("../utils");
const utils_2 = require("../vite/plugins/vitejs/utils");
const { preprocess: preprocessHtml } = require('../../lib/preprocess');
const TEMPLATE_BLOCK_RE = /<template\b[^>]*>([\s\S]*?)<\/template>/i;
const ROOT_SCROLL_VIEW_ATTR_RE = /^\s+style\s*=\s*(["'])\s*flex\s*:\s*1\s*;?\s*\1\s*$/;
const APP_ROOT_SCROLL_VIEW_RE = /^\s*<!--\s*#ifdef APP\s*-->\s*<scroll-view([^>]*)>[\s\S]*<\/scroll-view>\s*<!--\s*#endif\s*-->\s*$/;
const SPLIT_APP_ROOT_SCROLL_VIEW_RE = /^\s*<!--\s*#ifdef APP\s*-->\s*<scroll-view([^>]*)>\s*<!--\s*#endif\s*-->[\s\S]*<!--\s*#ifdef APP\s*-->\s*<\/scroll-view>\s*<!--\s*#endif\s*-->\s*$/;
/**
* 批量定位由 `#ifdef APP` 包裹的根 scroll-view 需要移除的范围。
* 只返回需要修改的行列号,不修改文件,也不返回修改后的文件内容。
*/
function resolveAppRootScrollViewEditRanges(vueFiles, inputDir) {
const result = {};
vueFiles.forEach((file) => {
const filename = resolveVueFilename(inputDir, file);
if (!(0, fs_extra_1.existsSync)(filename)) {
return;
}
const content = (0, fs_extra_1.readFileSync)(filename, 'utf8');
const ranges = resolveAppRootScrollViewEditRangesByCode(content, filename);
if (ranges.length) {
result[file] = ranges;
}
});
return result;
}
exports.resolveAppRootScrollViewEditRanges = resolveAppRootScrollViewEditRanges;
/**
* 蒸汽模式下,页面根节点会自动补一个 scroll-view。
* 这里仅用正则做精确匹配:命中范围宁可保守,也不能误报。
*/
function hasAppRootScrollViewWrappedByIfdef(code) {
const templateContent = getTemplateContent(code);
if (!templateContent) {
return false;
}
return (matchesAppRootScrollViewTemplate(templateContent, APP_ROOT_SCROLL_VIEW_RE) ||
matchesAppRootScrollViewTemplate(templateContent, SPLIT_APP_ROOT_SCROLL_VIEW_RE));
}
exports.hasAppRootScrollViewWrappedByIfdef = hasAppRootScrollViewWrappedByIfdef;
/**
* 仅在 dom2 页面整文件预处理时定位需要提示优化建议的根 scroll-view 节点。
*/
function resolveDom2RootScrollViewWarnLocation(code, filename, isVueSubRequest) {
if (process.env.UNI_PLATFORM !== 'app' ||
process.env.UNI_APP_X_DOM2 !== 'true' ||
isVueSubRequest ||
!(0, json_1.parseUniXPageOptions)(filename) ||
!code.includes('scroll-view') ||
!code.includes('#ifdef APP')) {
return;
}
if (!hasAppRootScrollViewWrappedByIfdef(code)) {
return;
}
return resolveAppRootScrollViewNodeLocByCode(code, filename);
}
exports.resolveDom2RootScrollViewWarnLocation = resolveDom2RootScrollViewWarnLocation;
function warnDom2RootScrollView(code, filename, isVueSubRequest) {
const location = resolveDom2RootScrollViewWarnLocation(code, filename, isVueSubRequest);
if (!location) {
return;
}
(0, logs_1.onCompileLog)('warn', {
message: messages_1.M['dom2.root.scroll.view'],
name: 'Warn',
loc: location.loc,
}, createWarnCodeFrameSource(location), (0, utils_1.normalizePath)((0, path_1.relative)(process.env.UNI_INPUT_DIR, filename)));
}
exports.warnDom2RootScrollView = warnDom2RootScrollView;
function resolveVueFilename(inputDir, file) {
if ((0, path_1.isAbsolute)(file)) {
const root = (0, path_1.parse)(file).root;
// HBuilderX/uni-app 里页面路径可能写成 `/pages/a/b.uvue`,
// 这种是项目内绝对路径,不是磁盘绝对路径,需要仍然基于 inputDir 解析。
if (root === '/' || root === '\\') {
return (0, path_1.resolve)(inputDir, removeLeadingRootSlash(file));
}
return file;
}
return (0, path_1.resolve)(inputDir, file);
}
function removeLeadingRootSlash(file) {
let index = 0;
while (file.charAt(index) === '/' || file.charAt(index) === '\\') {
index++;
}
return file.slice(index);
}
function getTemplateContent(code) {
return code.match(TEMPLATE_BLOCK_RE)?.[1];
}
function matchesAppRootScrollViewTemplate(template, regex) {
const match = template.match(regex);
return !!match && ROOT_SCROLL_VIEW_ATTR_RE.test(match[1]);
}
function resolveAppRootScrollViewNodeLocByCode(code, filename) {
const template = parseSfcTemplate(code, filename);
if (!template) {
return;
}
const children = template.ast.children;
if (children.length !== 3) {
return;
}
const [, scrollViewNode] = children;
if (!isRootScrollView(scrollViewNode)) {
return;
}
return {
loc: createStartTagLoc(code, scrollViewNode),
source: resolveStartTagSource(scrollViewNode),
};
}
function createStartTagLoc(code, node) {
const source = node.loc.source || '';
const endOffsetInSource = source.indexOf('>');
if (endOffsetInSource === -1) {
return {
start: node.loc.start,
end: node.loc.end,
};
}
return (0, utils_2.offsetToStartAndEnd)(code, node.loc.start.offset, node.loc.start.offset + endOffsetInSource + 1);
}
function resolveStartTagSource(node) {
const source = node.loc.source || '';
const endOffsetInSource = source.indexOf('>');
if (endOffsetInSource === -1) {
return source;
}
return source.slice(0, endOffsetInSource + 1);
}
function createWarnCodeFrameSource(location) {
return `${'\n'.repeat(Math.max(location.loc.start.line - 1, 0))}${location.source}`;
}
function resolveAppRootScrollViewEditRangesByCode(code, filename) {
const template = parseSfcTemplate(code, filename);
if (!template) {
return [];
}
const children = template.ast.children;
if (children.length !== 3) {
return [];
}
const [ifdefNode, scrollViewNode, endifNode] = children;
if (!isAppIfdefComment(ifdefNode) ||
!isRootScrollView(scrollViewNode) ||
!isEndifComment(endifNode)) {
return [];
}
// 使用项目既有的条件编译实现先跑一遍,再交给 Vue 编译器确认 APP 分支根节点。
if (!isPreprocessedRootScrollView(template.content, filename)) {
return [];
}
return createRootScrollViewEditRanges(ifdefNode, scrollViewNode, endifNode);
}
exports.resolveAppRootScrollViewEditRangesByCode = resolveAppRootScrollViewEditRangesByCode;
function parseSfcTemplate(code, filename) {
const { descriptor, errors } = (0, compiler_sfc_1.parse)(code, {
filename,
sourceMap: false,
});
if (errors.length || !descriptor.template?.ast) {
return;
}
return {
content: descriptor.template.content,
ast: descriptor.template.ast,
};
}
function isPreprocessedRootScrollView(content, filename) {
try {
const preprocessed = preprocessHtml(content, createAppPreContext(), {
type: 'html',
});
const template = parseSfcTemplate(`<template>${preprocessed}</template>`, filename);
const root = template?.ast.children[0];
return (!!root && template.ast.children.length === 1 && root.tag === 'scroll-view');
}
catch (e) {
return false;
}
}
function createAppPreContext() {
// 这里只声明本函数需要的 APP/UVue 上下文,避免改动全局条件编译上下文。
return {
APP: true,
APP_UVUE: true,
UNI_APP_X: true,
VUE3: true,
VUE3_VAPOR: true,
};
}
function isAppIfdefComment(node) {
return (node.type === 3 /* NodeTypes.COMMENT */ && node.content?.trim() === '#ifdef APP');
}
function isEndifComment(node) {
return node.type === 3 /* NodeTypes.COMMENT */ && node.content?.trim() === '#endif';
}
function isRootScrollView(node) {
return (node.type === 1 /* NodeTypes.ELEMENT */ &&
node.tag === 'scroll-view' &&
hasOnlyFlexStyle(node));
}
function hasOnlyFlexStyle(node) {
if (!node.props || node.props.length !== 1) {
return false;
}
const style = node.props[0];
return (style.type === 6 /* NodeTypes.ATTRIBUTE */ &&
style.name === 'style' &&
!!style.value &&
normalizeFlexStyle(style.value.content) === 'flex:1');
}
function normalizeFlexStyle(style) {
let normalized = '';
for (let i = 0; i < style.length; i++) {
const char = style.charAt(i);
if (char !== ' ' && char !== '\t' && char !== '\n' && char !== '\r') {
normalized += char;
}
}
if (normalized.endsWith(';')) {
return normalized.slice(0, -1);
}
return normalized;
}
function createRootScrollViewEditRanges(ifdefNode, scrollViewNode, endifNode) {
const children = scrollViewNode.children || [];
if (!children.length) {
return [createEditRange(ifdefNode, endifNode)];
}
const firstChild = children[0];
const lastChild = children[children.length - 1];
// 兼容如下写法:条件编译分别包裹 scroll-view 的开始标签和结束标签。
// <!-- #ifdef APP -->
// <scroll-view style="flex:1">
// <!-- #endif -->
// ...
// <!-- #ifdef APP -->
// </scroll-view>
// <!-- #endif -->
if (isEndifComment(firstChild) && isAppIfdefComment(lastChild)) {
return [
createEditRangeByLoc(ifdefNode.loc.start, firstChild.loc.end),
createEditRangeByLoc(lastChild.loc.start, endifNode.loc.end),
];
}
return [
createEditRangeByLoc(ifdefNode.loc.start, firstChild.loc.start, true),
createEditRangeByLoc(lastChild.loc.end, endifNode.loc.end),
];
}
function createEditRange(startNode, endNode) {
return createEditRangeByLoc(startNode.loc.start, endNode.loc.end);
}
function createEditRangeByLoc(start, end, preserveEndIndent = false) {
const range = {
start: toPosition(start),
end: toPosition(end),
preserveLineBreaks: true,
};
if (preserveEndIndent) {
range.preserveEndIndent = true;
}
return range;
}
function toPosition(loc) {
return {
line: loc.line,
column: loc.column,
};
}
@@ -0,0 +1,8 @@
import type { UasmTransformOptions } from '../uasm';
import type { UniVitePlugin } from '../vite';
export interface UniVaporScriptPluginOptions {
sharedDataLibName?: string;
sharedDataLibAsGlobal?: boolean;
uasm?: UasmTransformOptions;
}
export declare function uniVaporScriptPlugin(options?: UniVaporScriptPluginOptions): UniVitePlugin;
+32
View File
@@ -0,0 +1,32 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniVaporScriptPlugin = void 0;
const uts_1 = require("../uts");
const extApi_1 = require("../uts/extApi");
const utils_1 = require("../utils");
const scriptMacros_1 = require("../uts/scriptMacros");
const sharedData_1 = require("./sharedData");
function uniVaporScriptPlugin(options = {}) {
const { uasm, ...sharedData } = options;
const { D2SP } = (0, utils_1.requireUniHelpers)();
const nodeEnv = process.env.UNI_NODE_ENV || process.env.NODE_ENV;
/**
* 鸿蒙平台push、一键登录必须获取摇树结果,因此在非开发模式下或鸿蒙平台必须执行摇树逻辑
*/
const extApi = (0, utils_1.isNormalCompileTarget)() &&
(nodeEnv !== 'development' ||
process.env.UNI_UTS_PLATFORM === 'app-harmony')
? (0, extApi_1.initUts2jsExtApiOptions)()
: undefined;
return D2SP({
typescript: (0, uts_1.resolveUTSCompiler)().getTypeScript(),
createUniAppXScriptMacrosTransformer: scriptMacros_1.createUniAppXScriptMacrosTransformer,
extApi,
uasm,
sharedData: {
...(0, sharedData_1.initUts2jsSharedDataOptions)(),
...sharedData,
},
});
}
exports.uniVaporScriptPlugin = uniVaporScriptPlugin;
@@ -0,0 +1,9 @@
import type { Plugin } from 'vite';
export declare function uniSharedDataPlugin(): Plugin;
export declare function initSourceFileCallback(): ((sourceFile: import('typescript').SourceFile) => void) | undefined;
export declare function initUts2jsSharedDataOptions(): {
resolveFieldMeta(name: string): {
fieldId: number;
};
createSharedDataTransformer: any;
} | undefined;
@@ -0,0 +1,60 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initUts2jsSharedDataOptions = exports.initSourceFileCallback = exports.uniSharedDataPlugin = void 0;
const uts_1 = require("../uts");
const pages_1 = require("../json/pages");
const utils_1 = require("../utils");
const asset_1 = require("../vite/plugins/vitejs/plugins/asset");
const x_1 = require("../x");
const manifest_1 = require("../json/uni-x/manifest");
const manifest_2 = require("../json/manifest");
function initSharedDataOptions() {
const compiler = require('@dcloudio/compiler-vapor-dom2');
const manifest = (0, manifest_2.parseManifestJsonOnce)(process.env.UNI_INPUT_DIR);
return {
platform: process.env.UNI_UTS_PLATFORM,
compilerVaporDom2: compiler,
utsCompiler: (0, uts_1.resolveUTSCompiler)(),
isUniPageFile: pages_1.isUniPageFile,
getSharedDataResult: compiler.getSharedDataResult,
getAssetFilenameById: asset_1.getAssetFilenameById,
uvueScriptEngine: (0, x_1.isUniAppXAndroidNative)() ? 'native' : 'js',
compilerVersion: process.env.HX_Version || process.env.UNI_COMPILER_VERSION,
androidOptions: (0, x_1.isUniAppXAndroidJsEngine)()
? {
package: process.env.UNI_COMPILE_TARGET === 'ext-api'
? 'io.dcloud.uniapp.extapi'
: (0, manifest_1.parseUniXAppAndroidPackage)(manifest.appid),
}
: undefined,
};
}
function uniSharedDataPlugin() {
return (0, utils_1.requireUniHelpers)().USDP(initSharedDataOptions());
}
exports.uniSharedDataPlugin = uniSharedDataPlugin;
function initSourceFileCallback() {
if (process.env.UNI_APP_X_DOM2 === 'true' && (0, x_1.isUniAppXAndroidNative)()) {
const { TSDBSF } = (0, utils_1.requireUniHelpers)();
const options = initSharedDataOptions();
return (sourceFile) => {
TSDBSF(sourceFile, options);
};
}
}
exports.initSourceFileCallback = initSourceFileCallback;
function initUts2jsSharedDataOptions() {
if (process.env.UNI_APP_X_DOM2 === 'true') {
const uniHelpers = (0, utils_1.requireUniHelpers)();
if (typeof uniHelpers.CSDT !== 'function') {
throw new Error('DOM2 requires the SharedData transformer (CSDT)');
}
return {
resolveFieldMeta(name) {
return require('@dcloudio/compiler-vapor-dom2').resolveSharedDataFieldMeta(name);
},
createSharedDataTransformer: uniHelpers.CSDT,
};
}
}
exports.initUts2jsSharedDataOptions = initUts2jsSharedDataOptions;
+16
View File
@@ -0,0 +1,16 @@
import type { CompilerError, SFCDescriptor } from '@vue/compiler-sfc';
export declare function initVueTemplateCompilerExtraOptions(descriptor: SFCDescriptor): {
root: string;
platform: keyof UniApp.PagesJsonPagePlatformStyle;
componentType: string;
filename: string;
relativeFilename: string;
helper: any;
enableRootScrollViewTransform: boolean;
rootScrollView: import("src/json/uni-x").UniXPageOptions | undefined;
scriptCppBlocks: any;
onVueTemplateCompileLog(type: 'warn' | 'error', error: CompilerError): void;
r: any;
className: any;
inlineRender: boolean;
};
+37
View File
@@ -0,0 +1,37 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.initVueTemplateCompilerExtraOptions = void 0;
const path_1 = __importDefault(require("path"));
const utils_1 = require("../utils");
const json_1 = require("../json");
const vue_1 = require("../vue");
function initVueTemplateCompilerExtraOptions(descriptor) {
const filename = (0, utils_1.normalizePath)(descriptor.filename.split('?')[0]);
const relativeFilename = (0, utils_1.normalizePath)(path_1.default.relative(process.env.UNI_INPUT_DIR, filename));
const rootScrollView = (0, json_1.parseUniXPageOptions)(filename);
const componentType = rootScrollView || (0, json_1.isUniPageFile)(filename) ? 'page' : 'component';
const isDynamic = process.env.UNI_APP_X_DOM2_DYNAMIC === 'true';
const helper = (0, utils_1.requireUniHelpers)();
return {
root: (0, utils_1.normalizePath)(process.env.UNI_INPUT_DIR),
platform: process.env.UNI_UTS_PLATFORM,
componentType,
filename,
relativeFilename,
helper,
enableRootScrollViewTransform: true,
// 仅页面透传 rootScrollView,避免非页面组件误触发 ROOT 自动包裹逻辑。
rootScrollView: componentType === 'page' ? rootScrollView : undefined,
scriptCppBlocks: descriptor.scriptCppBlocks,
onVueTemplateCompileLog(type, error) {
return (0, vue_1.onVueTemplateCompileLog)(type, error, descriptor.source, relativeFilename);
},
r: helper.K,
className: helper.GCN(descriptor.filename, process.env.UNI_INPUT_DIR),
inlineRender: !isDynamic && process.env.UNI_UTS_PLATFORM === 'app-android',
};
}
exports.initVueTemplateCompilerExtraOptions = initVueTemplateCompilerExtraOptions;
+38
View File
@@ -0,0 +1,38 @@
interface EasycomOption {
platform: UniApp.PLATFORM;
isX?: boolean;
dirs?: string[];
rootDir: string;
extensions: string[];
autoscan?: boolean;
custom?: EasycomCustom;
}
export interface EasycomMatcher {
name: string;
pattern: RegExp;
replacement: string;
dom2IncompatibleFile?: string;
}
interface EasycomCustom {
[key: string]: string;
}
export declare function initEasycoms(inputDir: string, { dirs, platform, isX, }: {
dirs: string[];
platform: UniApp.PLATFORM;
isX?: boolean;
}): {
easyComOptions: EasycomOption;
filter: (id: unknown) => boolean;
refresh(): void;
easycoms: EasycomMatcher[];
};
export declare const initEasycomsOnce: typeof initEasycoms;
export declare function matchEasycom(tag: string): string | false | undefined;
export declare function addImportDeclaration(importDeclarations: string[], local: string, source: string, imported?: string): string;
export declare function genResolveEasycomCode(importDeclarations: string[], code: string, name: string): string;
export declare const UNI_EASYCOM_EXCLUDE: RegExp[];
export declare function getUTSEasyComAutoImports(): Record<string, [[string, string]]>;
export declare function addUTSEasyComAutoImports(source: string, imports: [string, string]): void;
export declare function genUTSComponentPublicInstanceIdent(tagName: string): string;
export declare function genUTSComponentPublicInstanceImported(root: string, fileName: string): string;
export {};
+375
View File
@@ -0,0 +1,375 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.genUTSComponentPublicInstanceImported = exports.genUTSComponentPublicInstanceIdent = exports.addUTSEasyComAutoImports = exports.getUTSEasyComAutoImports = exports.UNI_EASYCOM_EXCLUDE = exports.genResolveEasycomCode = exports.addImportDeclaration = exports.matchEasycom = exports.initEasycomsOnce = exports.initEasycoms = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const debug_1 = __importDefault(require("debug"));
const shared_1 = require("@vue/shared");
const pluginutils_1 = require("@rollup/pluginutils");
const uni_shared_1 = require("@dcloudio/uni-shared");
const x_1 = require("./x");
const utils_1 = require("./utils");
const pages_1 = require("./json/pages");
const messages_1 = require("./messages");
const uts_1 = require("./uts");
const utsUtils_1 = require("./utsUtils");
const debugEasycom = (0, debug_1.default)('uni:easycom');
const easycoms = [];
const easycomsCache = new Map();
const easycomsInvalidCache = new Set();
let hasEasycom = false;
function clearEasycom() {
easycoms.length = 0;
easycomsCache.clear();
easycomsInvalidCache.clear();
}
function initEasycoms(inputDir, { dirs, platform, isX, }) {
const componentsDir = path_1.default.resolve(inputDir, 'components');
const uniModulesDir = path_1.default.resolve(inputDir, 'uni_modules');
const initEasycomOptions = (pagesJson) => {
// 初始化时,从once中读取缓存,refresh时,实时读取
const { easycom } = pagesJson || (0, pages_1.parsePagesJson)(inputDir, platform, false);
const easycomOptions = {
platform,
isX,
dirs: easycom && easycom.autoscan === false
? [...dirs] // 禁止自动扫描
: [
...dirs,
componentsDir,
...initUniModulesEasycomDirs(uniModulesDir),
],
rootDir: inputDir,
autoscan: !!(easycom && easycom.autoscan),
custom: (easycom && easycom.custom) || {},
extensions: [...(isX ? ['.uvue'] : []), ...['.vue', '.jsx', '.tsx']],
};
debugEasycom(easycomOptions);
return easycomOptions;
};
const easyComOptions = initEasycomOptions((0, pages_1.parsePagesJsonOnce)(inputDir, platform));
const initUTSEasycom = () => {
(0, uts_1.initUTSComponents)(inputDir, platform).forEach((item) => {
const index = easycoms.findIndex((easycom) => item.name === easycom.name);
if (index > -1) {
easycoms.splice(index, 1, item);
}
else {
easycoms.push(item);
}
});
if (isX && globalThis.uts2jsSourceCodeMap) {
;
globalThis.uts2jsSourceCodeMap.initUts2jsEasycom(easycoms);
}
// UTS / customElements 组件是在 initEasycom 之后补充进去的,
// 这里补一次状态,避免项目里只有这类组件时被误判为没有 easycom。
hasEasycom = !!easycoms.length;
};
const initUTSEasycomCustomElements = () => {
(0, uts_1.initUTSCustomElements)(inputDir, platform).forEach((item) => {
const index = easycoms.findIndex((easycom) => item.name === easycom.name);
if (index > -1) {
easycoms.splice(index, 1, item);
}
else {
easycoms.push(item);
}
});
};
const supportCustomElements = isX && process.env.UNI_APP_X_DOM2 !== 'true';
// ext-api 模式下,不存在 easycom 特性
if (process.env.UNI_COMPILE_TARGET !== 'ext-api') {
clearEasycom();
(0, uts_1.clearUTSComponents)();
(0, uts_1.clearUTSCustomElements)();
initEasycom(easyComOptions);
// dom2 模式下,不需要注册 customElements 组件
if (supportCustomElements) {
initUTSEasycomCustomElements();
}
initUTSEasycom();
}
const componentExtNames = isX ? 'uvue|vue' : 'vue';
const res = {
easyComOptions,
filter: (0, pluginutils_1.createFilter)([
'components/*/*.(' + componentExtNames + '|jsx|tsx)',
'uni_modules/*/components/*/*.(' + componentExtNames + '|jsx|tsx)',
'utssdk/*/**/*.(' + componentExtNames + ')',
'uni_modules/*/utssdk/*/*.(' + componentExtNames + ')',
...(supportCustomElements
? ['uni_modules/*/customElements/*/*.uts']
: []),
], [], {
resolve: inputDir,
}),
refresh() {
res.easyComOptions = initEasycomOptions();
if (process.env.UNI_COMPILE_TARGET !== 'ext-api') {
clearEasycom();
(0, uts_1.clearUTSComponents)();
(0, uts_1.clearUTSCustomElements)();
initEasycom(res.easyComOptions);
if (supportCustomElements) {
initUTSEasycomCustomElements();
}
initUTSEasycom();
}
},
easycoms,
};
return res;
}
exports.initEasycoms = initEasycoms;
exports.initEasycomsOnce = (0, uni_shared_1.once)(initEasycoms);
function initUniModulesEasycomDirs(uniModulesDir, componentsDir = 'components') {
if (!fs_1.default.existsSync(uniModulesDir)) {
return [];
}
return fs_1.default
.readdirSync(uniModulesDir)
.map((uniModuleDir) => {
const uniModuleComponentsDir = path_1.default.resolve(uniModulesDir, uniModuleDir, componentsDir);
if (fs_1.default.existsSync(uniModuleComponentsDir)) {
return uniModuleComponentsDir;
}
})
.filter(Boolean);
}
function initEasycom({ platform, isX, dirs, rootDir, custom, extensions, }) {
rootDir = (0, utils_1.normalizePath)(rootDir);
const easycomsObj = Object.create(null);
if (dirs && dirs.length && rootDir) {
const autoEasyComObj = initAutoScanEasycoms(platform, dirs, rootDir, extensions);
if (isX) {
Object.keys(autoEasyComObj).forEach((tagName) => {
let source = autoEasyComObj[tagName];
tagName = tagName.slice(1, -1);
if (path_1.default.isAbsolute(source) && source.startsWith(rootDir)) {
source = '@/' + (0, utils_1.normalizePath)(path_1.default.relative(rootDir, source));
}
// 加密插件easycom类型导入
if (source.includes('?uts-proxy')) {
const moduleId = path_1.default.basename(source.split('?uts-proxy')[0]);
source = `uts.sdk.modules.${(0, shared_1.camelize)(moduleId)}`;
}
const ident = genUTSComponentPublicInstanceIdent(tagName);
addUTSEasyComAutoImports(source, [ident, ident]);
});
}
(0, shared_1.extend)(easycomsObj, autoEasyComObj);
}
if (custom) {
Object.keys(custom).forEach((name) => {
const componentPath = custom[name];
easycomsObj[name] = componentPath.startsWith('@/')
? (0, utils_1.normalizePath)(path_1.default.join(rootDir, componentPath.slice(2)))
: componentPath;
});
}
Object.keys(easycomsObj).forEach((name) => {
easycoms.push({
name: name.startsWith('^') && name.endsWith('$') ? name.slice(1, -1) : name,
pattern: new RegExp(name),
replacement: easycomsObj[name],
});
});
debugEasycom(easycoms);
hasEasycom = !!easycoms.length;
return easycoms;
}
function matchEasycom(tag) {
if (!hasEasycom) {
return;
}
let source = easycomsCache.get(tag);
if (source) {
return source;
}
if (easycomsInvalidCache.has(tag)) {
return false;
}
const matcher = easycoms.find((matcher) => matcher.pattern.test(tag));
if (!matcher) {
easycomsInvalidCache.add(tag);
return false;
}
// dom2 不支持旧版 uni-app 兼容模式组件,这里在 easycom 真正命中时再报错,
// 避免扫描阶段就对未使用的插件组件产生误报。
if (process.env.UNI_APP_X_DOM2 === 'true' && matcher.dom2IncompatibleFile) {
throw new Error(messages_1.M['dom2.compatible.component']
.replace('{name}', `<${tag}>`)
.replace('{file}', matcher.dom2IncompatibleFile));
}
source = tag.replace(matcher.pattern, matcher.replacement);
easycomsCache.set(tag, source);
debugEasycom('matchEasycom', tag, source);
// 检查 H5 专用组件 ask163203
const H5_ONLY_COMPONENTS = ['custom-tab-bar'];
if (H5_ONLY_COMPONENTS.includes(tag) && process.env.UNI_PLATFORM !== 'h5') {
console.warn(`[uni-app] 组件 <${tag}> 是 H5 平台专用组件,在 ${process.env.UNI_PLATFORM} 平台使用可能导致错误。如果你要引入自定义 tabBar 可重命名为其他名称。`);
}
return source;
}
exports.matchEasycom = matchEasycom;
const isDir = (path) => {
const stat = fs_1.default.lstatSync(path);
if (stat.isDirectory()) {
return true;
}
else if (stat.isSymbolicLink()) {
return fs_1.default.lstatSync(fs_1.default.realpathSync(path)).isDirectory();
}
return false;
};
function initAutoScanEasycom(platform, dir, rootDir, extensions) {
if (!path_1.default.isAbsolute(dir)) {
dir = path_1.default.resolve(rootDir, dir);
}
const easycoms = Object.create(null);
if (!fs_1.default.existsSync(dir)) {
return easycoms;
}
const isDevX = process.env.UNI_HX_VERSION_DEV === 'true' &&
process.env.UNI_APP_X === 'true';
const isMp = platform.startsWith('mp-');
const is_uni_modules = path_1.default.basename(path_1.default.resolve(dir, '../..')) === 'uni_modules';
const has_uts_sdk_dir = fs_1.default.existsSync(path_1.default.resolve(dir, '../utssdk'));
const is_easycom_encrypt_uni_modules = // uni_modules模式不需要此逻辑
process.env.UNI_COMPILE_TARGET !== 'uni_modules' &&
is_uni_modules &&
// 前端加密插件,不能包含utssdk目录
fs_1.default.existsSync(path_1.default.resolve(dir, '../encrypt')) &&
!has_uts_sdk_dir;
const uni_modules_plugin_id = is_easycom_encrypt_uni_modules && path_1.default.basename(path_1.default.resolve(dir, '..'));
fs_1.default.readdirSync(dir).forEach((name) => {
const folder = path_1.default.resolve(dir, name);
if (!isDir(folder)) {
return;
}
if (isDevX) {
if (has_uts_sdk_dir &&
process.env.UNI_UTS_PLATFORM &&
process.env.UNI_UTS_PLATFORM !== 'web' &&
(0, uni_shared_1.isBuiltInComponent)(name)) {
// dev下,如果是内置组件,且存在utssdk目录,则判断utssdk下是否存在当前平台,如果不存在,则跳过
const utsSdkPlatformDir = path_1.default.resolve(dir, '../utssdk', process.env.UNI_UTS_PLATFORM);
if (!fs_1.default.existsSync(utsSdkPlatformDir)) {
return;
}
}
}
const importDir = (0, utils_1.normalizePath)(folder);
const files = fs_1.default.readdirSync(folder);
// 读取文件夹文件列表,比对文件名(fs.existsSync在大小写不敏感的系统会匹配不准确)
for (let i = 0; i < extensions.length; i++) {
const ext = extensions[i];
if (files.includes(name + ext)) {
easycoms[`^${name}$`] =
// mp平台,这里不处理,由uniEntryPlugin处理
is_easycom_encrypt_uni_modules && !isMp
? (0, utils_1.normalizePath)(path_1.default.join(rootDir, `uni_modules/${uni_modules_plugin_id}?${(0, x_1.isUniAppXAndroidNative)() ? 'uts-proxy' : 'uni_helpers'}`))
: `${importDir}/${name}${ext}`;
break;
}
}
});
return easycoms;
}
function initAutoScanEasycoms(platform, dirs, rootDir, extensions) {
const conflict = {};
const res = dirs.reduce((easycoms, dir) => {
const curEasycoms = initAutoScanEasycom(platform, dir, rootDir, extensions);
Object.keys(curEasycoms).forEach((name) => {
// Use the first component when name conflict
const componentPath = easycoms[name];
if (!componentPath) {
easycoms[name] = curEasycoms[name];
}
else {
;
(conflict[componentPath] || (conflict[componentPath] = [])).push(normalizeComponentPath(curEasycoms[name], rootDir));
}
});
return easycoms;
}, Object.create(null));
const conflictComponents = Object.keys(conflict);
if (conflictComponents.length) {
console.warn(messages_1.M['easycom.conflict']);
conflictComponents.forEach((com) => {
console.warn([normalizeComponentPath(com, rootDir), conflict[com]].join(','));
});
}
return res;
}
function normalizeComponentPath(componentPath, rootDir) {
return (0, utils_1.normalizePath)(path_1.default.relative(rootDir, componentPath));
}
function addImportDeclaration(importDeclarations, local, source, imported) {
importDeclarations.push(createImportDeclaration(local, source, imported));
return local;
}
exports.addImportDeclaration = addImportDeclaration;
function createImportDeclaration(local, source, imported) {
if (imported && local) {
return `import { ${imported} as ${local} } from '${source}';`;
}
if (local) {
return `import ${local} from '${source}';`;
}
return `import '${source}';`;
}
const RESOLVE_EASYCOM_IMPORT_CODE = `import { resolveDynamicComponent as __resolveDynamicComponent } from 'vue';import { resolveEasycom } from '@dcloudio/uni-app';`;
function genResolveEasycomCode(importDeclarations, code, name) {
if (process.env.UNI_APP_X_DOM2 === 'true' ||
// 内部 dev 版本,需要本地开发内置组件,比如web-view,此时需要直接返回本地easycom,不然会找到基座内置的
(process.env.UNI_HX_VERSION_DEV === 'true' &&
process.env.UNI_APP_X === 'true')) {
// dom2 模式下,为了性能,不再考虑优先级问题,如果开发者需要区别,可以手动导入为其他名称
return name;
}
if (!importDeclarations.includes(RESOLVE_EASYCOM_IMPORT_CODE)) {
importDeclarations.push(RESOLVE_EASYCOM_IMPORT_CODE);
}
return `resolveEasycom(${code
.replace('_resolveComponent', '__resolveDynamicComponent')
// 移除 maybeSelfReference 逻辑,easycom 优先级高于自引用组件
.replace(', true)', ')')}, ${name})`;
}
exports.genResolveEasycomCode = genResolveEasycomCode;
exports.UNI_EASYCOM_EXCLUDE = [/@dcloudio\/uni-h5/];
const utsEasyComAutoImports = {};
function getUTSEasyComAutoImports() {
return utsEasyComAutoImports;
}
exports.getUTSEasyComAutoImports = getUTSEasyComAutoImports;
function addUTSEasyComAutoImports(source, imports) {
if (!utsEasyComAutoImports[source]) {
utsEasyComAutoImports[source] = [imports];
}
else {
if (!utsEasyComAutoImports[source].find((item) => item[0] === imports[0])) {
utsEasyComAutoImports[source].push(imports);
}
}
}
exports.addUTSEasyComAutoImports = addUTSEasyComAutoImports;
function genUTSComponentPublicInstanceIdent(tagName) {
return (0, shared_1.capitalize)((0, shared_1.camelize)(tagName)) + 'ComponentPublicInstance';
}
exports.genUTSComponentPublicInstanceIdent = genUTSComponentPublicInstanceIdent;
function genUTSComponentPublicInstanceImported(root, fileName) {
root = (0, utils_1.normalizePath)(root);
if (path_1.default.isAbsolute(fileName) && fileName.startsWith(root)) {
fileName = (0, utils_1.normalizePath)(path_1.default.relative(root, fileName));
}
if (fileName.startsWith('@/')) {
return ((0, utsUtils_1.genUTSClassName)(fileName.replace('@/', '')) + 'ComponentPublicInstance');
}
return (0, utsUtils_1.genUTSClassName)(fileName) + 'ComponentPublicInstance';
}
exports.genUTSComponentPublicInstanceImported = genUTSComponentPublicInstanceImported;
@@ -0,0 +1,24 @@
export declare function initDefine(stringifyBoolean?: boolean): {
__X_STYLE_ISOLATION__: string | boolean;
__X_STYLE_ISOLATION_UP_ARROW__: string | boolean;
'process.env.UNI_APP_X_NEW_STYLE_ISOLATION': string | boolean;
'process.env.NODE_ENV': string;
'process.env.UNI_DEBUG': string | boolean;
'process.env.UNI_APP_ID': string;
'process.env.UNI_APP_NAME': string;
'process.env.UNI_APP_VERSION_NAME': string;
'process.env.UNI_APP_VERSION_CODE': string;
'process.env.UNI_PLATFORM': string;
'process.env.UNI_SUB_PLATFORM': string;
'process.env.UNI_MP_PLUGIN': string;
'process.env.UNI_SUBPACKAGE': string;
'process.env.UNI_COMPILER_VERSION': string;
'process.env.RUN_BY_HBUILDERX': string | boolean;
'process.env.UNI_AUTOMATOR_WS_ENDPOINT': string;
'process.env.UNI_AUTOMATOR_APP_WEBVIEW_SRC': string;
'process.env.UNI_CLOUD_PROVIDER': string;
'process.env.UNICLOUD_DEBUG': string;
'process.env.VUE_APP_PLATFORM': string;
'process.env.VUE_APP_DARK_MODE': string;
__UNI_PRELOAD_SHADOW_IMAGE__: string;
};
+72
View File
@@ -0,0 +1,72 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initDefine = void 0;
const utils_1 = require("../utils");
const env_1 = require("../hbx/env");
const json_1 = require("../json");
function initDefine(stringifyBoolean = false) {
const manifestJson = (0, json_1.parseManifestJsonOnce)(process.env.UNI_INPUT_DIR);
const platformManifestJson = (0, json_1.getPlatformManifestJsonOnce)();
const isRunByHBuilderX = (0, env_1.runByHBuilderX)();
const isDebug = !!manifestJson.debug;
const isX = process.env.UNI_APP_X === 'true';
const isNewStyleIsolation = process.env.UNI_APP_STYLE_ISOLATION_VERSION === '2';
// 目前仅微信小程序支持^穿透
const isNewStyleIsolationUpArrow = isNewStyleIsolation && process.env.UNI_PLATFORM === 'mp-weixin';
const isMP = process.env.UNI_PLATFORM && process.env.UNI_PLATFORM.startsWith('mp-');
process.env['UNI_APP_ID'] = manifestJson.appid;
const mpXDefine = {
__UNI_FEATURE_VIRTUAL_HOST__: isX && isMP && platformManifestJson.enableVirtualHost !== false,
};
const styleIsolation = stringifyBoolean
? JSON.stringify(isNewStyleIsolation)
: isNewStyleIsolation;
return {
...initCustomDefine(),
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
'process.env.UNI_DEBUG': stringifyBoolean
? JSON.stringify(isDebug)
: isDebug,
'process.env.UNI_APP_ID': JSON.stringify(manifestJson.appid || ''),
'process.env.UNI_APP_NAME': JSON.stringify(manifestJson.name || ''),
'process.env.UNI_APP_VERSION_NAME': JSON.stringify(manifestJson.versionName || ''),
'process.env.UNI_APP_VERSION_CODE': JSON.stringify(manifestJson.versionCode || ''),
'process.env.UNI_PLATFORM': JSON.stringify(process.env.UNI_PLATFORM),
'process.env.UNI_SUB_PLATFORM': JSON.stringify(process.env.UNI_SUB_PLATFORM || ''),
'process.env.UNI_MP_PLUGIN': JSON.stringify(process.env.UNI_MP_PLUGIN || ''),
'process.env.UNI_SUBPACKAGE': JSON.stringify(process.env.UNI_SUBPACKAGE || ''),
'process.env.UNI_COMPILER_VERSION': JSON.stringify(process.env.UNI_COMPILER_VERSION || ''),
'process.env.RUN_BY_HBUILDERX': stringifyBoolean
? JSON.stringify(isRunByHBuilderX)
: isRunByHBuilderX,
'process.env.UNI_AUTOMATOR_WS_ENDPOINT': JSON.stringify(process.env.UNI_AUTOMATOR_WS_ENDPOINT || ''),
'process.env.UNI_AUTOMATOR_APP_WEBVIEW_SRC': JSON.stringify(process.env.UNI_AUTOMATOR_APP_WEBVIEW_SRC || ''),
'process.env.UNI_CLOUD_PROVIDER': JSON.stringify(process.env.UNI_CLOUD_PROVIDER || ''),
'process.env.UNICLOUD_DEBUG': JSON.stringify(process.env.UNICLOUD_DEBUG || ''),
// 兼容旧版本
'process.env.VUE_APP_PLATFORM': JSON.stringify(process.env.UNI_PLATFORM || ''),
'process.env.VUE_APP_DARK_MODE': JSON.stringify(platformManifestJson.darkmode || false),
__UNI_PRELOAD_SHADOW_IMAGE__: JSON.stringify(process.env.UNI_PLATFORM === 'mp-weixin' ? (0, utils_1.getShadowImagePath)('grey') : ''),
...mpXDefine,
__X_STYLE_ISOLATION__: styleIsolation,
__X_STYLE_ISOLATION_UP_ARROW__: stringifyBoolean
? JSON.stringify(isNewStyleIsolationUpArrow)
: isNewStyleIsolationUpArrow,
// 下边这个主要是为web服务,因为ssr目前只能识别process.env中的内容
'process.env.UNI_APP_X_NEW_STYLE_ISOLATION': styleIsolation,
};
}
exports.initDefine = initDefine;
function initCustomDefine() {
let define = {};
if (process.env.UNI_CUSTOM_DEFINE) {
try {
define = JSON.parse(process.env.UNI_CUSTOM_DEFINE);
}
catch (e) { }
}
return Object.keys(define).reduce((res, name) => {
res['process.env.' + name] = JSON.stringify(define[name]);
return res;
}, {});
}
@@ -0,0 +1,2 @@
export { initDefine } from './define';
export { initAppProvide } from './provide';
+7
View File
@@ -0,0 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initAppProvide = exports.initDefine = void 0;
var define_1 = require("./define");
Object.defineProperty(exports, "initDefine", { enumerable: true, get: function () { return define_1.initDefine; } });
var provide_1 = require("./provide");
Object.defineProperty(exports, "initAppProvide", { enumerable: true, get: function () { return provide_1.initAppProvide; } });
@@ -0,0 +1,8 @@
export declare function initAppProvide(): {
__f__: string[];
crypto: string[];
'window.crypto': string[];
'global.crypto': string[];
'uni.getCurrentSubNVue': string[];
'uni.requireNativePlugin': string[];
};

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