Initial commit

This commit is contained in:
jiapengyu
2026-07-27 13:37:48 +08:00
commit ecba71e2a5
39123 changed files with 5989154 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" />
+20746
View File
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;
+252
View File
@@ -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;
}
}
+2
View File
@@ -0,0 +1,2 @@
/// <reference path="./base.d.ts" />
/// <reference path="./extension/index.d.ts" />
+2
View File
@@ -0,0 +1,2 @@
/// <reference path="./wx/index.d.ts" />
/// <reference path="./promisify/index.d.ts" />
+34
View File
@@ -0,0 +1,34 @@
declare namespace UniNamespace {
type PromisifySuccessResult<
P,
T extends {
success?: (...args: any[]) => void
},
R = void
> = P extends {
success: any
}
? R
: P extends { fail: any }
? R
: P extends { complete: any }
? R
: Promise<Parameters<Exclude<T['success'], undefined>>[0]>;
type ErrorFirstArray<T> = [any, T];
type PromisifySuccessResultLegacy<
P,
T extends {
success?: (...args: any[]) => void
}
> = P extends {
success: any
}
? void
: P extends { fail: any }
? void
: P extends { complete: any }
? void
: Promise<ErrorFirstArray<Parameters<Exclude<T['success'], undefined>>[0]>>;
}
@@ -0,0 +1,2 @@
/// <reference path="./common.d.ts" />
/// <reference path="./uni.d.ts" />
+140
View File
@@ -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;
}
+402
View File
@@ -0,0 +1,402 @@
import { AsyncOptions } from './Utils';
declare global {
namespace UniNamespace {
interface MapContext {
/**
* 获取当前地图中心的经纬度,返回的是 gcj02 坐标系,可以用于 uni.openLocation
*/
getCenterLocation(options: MapContextGetCenterLocationOptions): void;
/**
* 将地图中心移动到当前定位点,需要配合map组件的show-location使用
*/
moveToLocation(options: MapContextMoveToLocationOptions): void;
/**
* 平移marker,带动画
*/
translateMarker(options: MapContextTranslateMarkerOptions): void;
/**
* 缩放视野展示所有经纬度
*/
includePoints(options: MapContextIncludePointsOptions): void;
/**
* 获取当前地图的视野范围
*/
getRegion(options: MapContextGetRegionOptions): void;
/**
* 获取当前地图的缩放级别
*/
getScale(options: MapContextGetScaleOptions): void;
/**
* 添加个性化图层
*/
addCustomLayer?: (options: MapContextAddCustomLayerOptions) => void;
/**
* 创建自定义图片图层,图片会随着地图缩放而缩放
*/
addGroundOverlay(options: MapContextAddGroundOverlayOptions): void;
/**
* 添加 marker
*/
addMarkers(options: MapContextAddMarkersOptions): void;
/**
* 获取屏幕上的点对应的经纬度,坐标原点为地图左上角
*/
fromScreenLocation?: (options: MapContextFromScreenLocationOptions) => void;
/**
* 初始化点聚合的配置,未调用时采用默认配置
*/
initMarkerCluster(options: MapContextInitMarkerClusterOptions): void;
/**
* 沿指定路径移动 marker,用于轨迹回放等场景。动画完成时触发回调事件,若动画进行中,对同一 marker 再次调用 moveAlong 方法,前一次的动画将被打断。
*/
moveAlong(options: MapContextMoveAlongOptions): void;
/**
* 拉起地图APP选择导航。
*/
openMapApp(options: MapContextOpenMapAppOptions): void;
/**
* 移除个性化图层
*/
removeCustomLayer(options: MapContextRemoveCustomLayerOptions): void;
/**
* 移除自定义图片图层
*/
removeGroundOverlay(options: MapContextRemoveGroundOverlayOptions): void;
/**
* 移除 marker
*/
removeMarkers(options: MapContextRemoveMarkersOptions): void;
/**
* 设置地图中心点偏移,向后向下为增长,屏幕比例范围(0.25~0.75),默认偏移为[0.5, 0.5]
*/
setCenterOffset?: (options: MapContextSetCenterOffsetOptions) => void;
/**
* 获取经纬度对应的屏幕坐标,坐标原点为地图左上角。
*/
toScreenLocation?: (options: MapContextToScreenLocationOptions) => void;
/**
* 更新自定义图片图层。
*/
updateGroundOverlay(options: MapContextUpdateGroundOverlayOptions): void;
/**
* 监听地图事件。
*/
on(event: 'markerClusterCreate' | 'markerClusterClick', callback: (...args: any[]) => any): void;
/**
* 获取原生地图对象 plus.maps.Map
*/
$getAppMap(): any;
}
interface MapContextGetCenterLocationOptions extends AsyncOptions {
/**
* 接口调用成功的回调函数 res = { longitude: "经度", latitude: "纬度"}
*/
success?: (result: LocationObject) => void;
}
interface MapContextMoveToLocationOptions extends AsyncOptions {
/**
* 纬度,浮点数,范围为-90~90,负数表示南纬
*/
latitude?: number;
/**
* 经度,范围为-180~180,负数表示西经
*/
longitude?: number;
}
interface LocationObject {
/**
* 纬度,浮点数,范围为-90~90,负数表示南纬
*/
latitude: number;
/**
* 经度,范围为-180~180,负数表示西经
*/
longitude: number;
}
interface MapContextTranslateMarkerOptions extends AsyncOptions {
/**
* 指定marker
*/
markerId: number;
/**
* 指定marker移动到的目标点
*/
destination: LocationObject;
/**
* 移动过程中是否自动旋转marker
*/
autoRotate: boolean;
/**
* marker的旋转角度
*/
rotate: number;
/**
* 平移和旋转同时进行,默认值false(仅微信小程序2.13.0支持)
*/
moveWithRotate?: boolean;
/**
* 动画持续时长,默认值1000ms,平移与旋转分别计算
*/
duration?: number;
/**
* 动画结束回调函数
*/
animationEnd?: (result: any) => void;
}
interface MapContextIncludePointsOptions extends AsyncOptions {
/**
* 要显示在可视区域内的坐标点列表,[{latitude, longitude}]
*/
points: LocationObject[];
/**
* 坐标点形成的矩形边缘到地图边缘的距离,单位像素。格式为[上,右,下,左],安卓上只能识别数组第一项,上下左右的padding一致。开发者工具暂不支持padding参数。
*/
padding?: number[];
}
interface MapContextGetRegionOptions extends AsyncOptions {
/**
* 接口调用成功的回调函数,res = {southwest, northeast},西南角与东北角的经纬度
*/
success?: (result: MapContextGetRegionResult) => void;
}
interface MapContextGetRegionResult {
/**
* 西南角的经纬度
*/
southwest: LocationObject;
/**
* 东北角的经纬度
*/
northeast: LocationObject;
}
interface MapContextGetScaleOptions extends AsyncOptions {
/**
* 接口调用成功的回调函数,res = {scale}
*/
success?: (result: MapContextGetScaleResult) => void;
}
interface MapContextGetScaleResult {
/**
* 地图缩放级别
*/
scale: number;
}
interface MapContextAddCustomLayerOptions extends AsyncOptions {
/**
* 个性化图层id
*/
layerId: string;
}
interface MapContextAddGroundOverlayOptions extends AsyncOptions {
/**
* 图片图层 id
*/
id: string;
/**
* 图片路径,支持网络图片、临时路径、代码包路径
*/
src: string;
/**
* 图片覆盖的经纬度范围
*/
bounds: Bounds;
/**
* 是否可见
*/
visible?: boolean;
/**
* 图层绘制顺序
*/
zIndex?: number;
/**
* 图层透明度
*/
opacity?: number;
}
interface Bounds {
/**
* 西南角的经纬度
*/
southwest: LocationObject;
/**
* 东北角的经纬度
*/
northeast: LocationObject;
}
interface MapContextAddMarkersOptions extends AsyncOptions {
/**
* 同传入 map 组件的 marker 属性
*/
markers: any[];
/**
* 是否先清空地图上所有 marker
*/
clear: boolean;
}
interface MapContextFromScreenLocationOptions extends AsyncOptions {
/**
* x 坐标值
*/
x: number;
/**
* y 坐标值
*/
y: number;
/**
* 接口调用成功的回调函数
*/
success?: (result: LocationObject) => void;
}
interface MapContextInitMarkerClusterOptions extends AsyncOptions {
/**
* 启用默认的聚合样式
*/
enableDefaultStyle: boolean;
/**
* 点击已经聚合的标记点时是否实现聚合分离
*/
zoomOnClick: boolean;
/**
* 聚合算法的可聚合距离,即距离小于该值的点会聚合至一起,以像素为单位
*/
gridSize: number;
}
interface MapContextMoveAlongOptions extends AsyncOptions {
/**
* 指定 marker
*/
markerId: number;
/**
* 移动路径的坐标串,坐标点格式 {longitude, latitude}
*/
path: LocationObject[];
/**
* 根据路径方向自动改变 marker 的旋转角度
*/
autoRotate?: boolean;
/**
* 平滑移动的时间
*/
duration: number;
}
interface MapContextOpenMapAppOptions extends AsyncOptions {
/**
* 目的地名称
*/
destination: string;
/**
* 目的地纬度
*/
latitude: number;
/**
* 目的地经度
*/
longitude: number;
}
interface MapContextRemoveCustomLayerOptions extends AsyncOptions {
/**
* 个性化图层id
*/
layerId: string;
}
interface MapContextRemoveGroundOverlayOptions extends AsyncOptions {
/**
* 图片图层 id
*/
id: string;
}
interface MapContextRemoveMarkersOptions extends AsyncOptions {
/**
* 要被删除的marker的id属性组成的数组
*/
markerIds: any[];
}
interface MapContextSetCenterOffsetOptions {
/**
* 偏移量,两位数组
*/
offset: number[];
/**
* 接口调用成功的回调函数
*/
success?: (result: any) => void;
/**
* 接口调用失败的回调函数
*/
fail?: (result: any) => void;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (result: any) => void;
}
interface MapContextToScreenLocationOptions extends AsyncOptions {
/**
* 纬度
*/
latitude: number;
/**
* 经度
*/
longitude: number;
}
interface MapContextUpdateGroundOverlayOptions extends AsyncOptions {
/**
* 图片图层 id
*/
id: string;
/**
* 图片路径,支持网络图片、临时路径、代码包路径
*/
src: string;
/**
* 图片路径,支持网络图片、临时路径、代码包路径
*/
bounds: Bounds;
/**
* 是否可见
*/
visible?: boolean;
/**
* 图层绘制顺序
*/
zIndex?: number;
/**
* 图层透明度
*/
opacity?: number;
}
}
interface Uni {
/**
* 创建并返回 map 上下文 mapContext 对象
*
* 文档: [http://uniapp.dcloud.io/api/location/map?id=createmapcontext](http://uniapp.dcloud.io/api/location/map?id=createmapcontext)
*/
createMapContext(mapId: string, currentComponent?: any): UniNamespace.MapContext;
}
}
+24
View File
@@ -0,0 +1,24 @@
declare namespace UniNamespace {
interface OnThemeChangeCallbackResult {
/**
* 主题名称
*/
theme: 'dark' | 'light';
}
type OnThemeChangeCallback = (res: OnThemeChangeCallbackResult) => void;
}
interface Uni {
/**
* 监听系统主题状态变化。
*
* 文档: [https://uniapp.dcloud.net.cn/api/system/theme.html#onthemechange](https://uniapp.dcloud.net.cn/api/system/theme.html#onthemechange)
*/
onThemeChange(callback: UniNamespace.OnThemeChangeCallback): void;
/**
* 取消监听系统主题状态变化。
*
* 文档: [https://uniapp.dcloud.net.cn/api/system/theme.html#offthemechange](https://uniapp.dcloud.net.cn/api/system/theme.html#offthemechange)
*/
offThemeChange(callback: UniNamespace.OnThemeChangeCallback): void;
}
+43
View File
@@ -0,0 +1,43 @@
declare namespace UniNamespace {
interface OnUnhandledRejectionCallbackResult {
/**
* 被拒绝的 Promise 对象
*/
promise: Promise<any>;
/**
* 拒绝原因,一般是一个 Error 对象
*/
reason: string;
}
/**
* 未处理的 Promise 拒绝事件的回调函数
*/
type OnUnhandledRejectionCallback = (result: OnUnhandledRejectionCallbackResult) => void;
}
interface Uni {
/**
* 监听未处理的 Promise 拒绝事件。该事件与 `App.onUnhandledRejection` 的回调时机与参数一致。
*
* **注意**
*
*
* - 安卓平台暂时不支持该事件
* - 所有的 unhandledRejection 都可以被这一监听捕获,但只有 Error 类型的才会在小程序后台触发报警。
*
* 最低基础库: `2.10.0`
*
* 文档: [https://developers.weixin.qq.com/miniprogram/dev/api/base/app/app-event/wx.onUnhandledRejection.html](https://developers.weixin.qq.com/miniprogram/dev/api/base/app/app-event/wx.onUnhandledRejection.html)
*/
onUnhandledRejection(callback: UniNamespace.OnUnhandledRejectionCallback): void;
/**
* 取消监听未处理的 Promise 拒绝事件
*
* 最低基础库: `2.10.0`
*
* 文档: [https://developers.weixin.qq.com/miniprogram/dev/api/base/app/app-event/wx.offUnhandledRejection.html](https://developers.weixin.qq.com/miniprogram/dev/api/base/app/app-event/wx.offUnhandledRejection.html)
*/
offUnhandledRejection(callback: UniNamespace.OnUnhandledRejectionCallback): void;
}
+14
View File
@@ -0,0 +1,14 @@
export interface AsyncOptions {
/**
* 接口调用成功的回调函数
*/
success?: (result: any) => void;
/**
* 接口调用失败的回调函数
*/
fail?: (result: any) => void;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (result: any) => void;
}
+5
View File
@@ -0,0 +1,5 @@
/// <reference path="./ThemeChange.d.ts" />
/// <reference path="./UnhandledRejectiond.d.ts" />
/// <reference path="./Error.d.ts" />
/// <reference path="./MapContext.d.ts" />
/// <reference path="./request.d.ts" />
+200
View File
@@ -0,0 +1,200 @@
declare namespace UniNamespace {
interface RequestOptions {
/**
* 资源url
*/
url: string;
/**
* 请求的参数
*/
data?: string | AnyObject | ArrayBuffer;
/**
* 设置请求的 headerheader 中不能设置 Referer。
*/
header?: any;
/**
* 默认为 GET
* 可以是:OPTIONSGETHEADPOSTPUTDELETETRACECONNECT
*/
method?: 'OPTIONS' | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT';
/**
* 超时时间
*/
timeout?: number;
/**
* 如果设为json,会尝试对返回的数据做一次 JSON.parse
*/
dataType?: string;
/**
* 设置响应的数据类型。合法值:text、arraybuffer
*/
responseType?: string;
/**
* 验证 ssl 证书
*/
sslVerify?: boolean;
/**
* 跨域请求时是否携带凭证
*/
withCredentials?: boolean;
/**
* DNS解析时优先使用 ipv4
*/
firstIpv4?: boolean;
/**
* 开启 http2
*/
enableHttp2?: boolean;
/**
* 开启 quic
*/
enableQuic?: boolean;
/**
* 开启 cache
*/
enableCache?: boolean;
/**
* 是否开启 HttpDNS 服务。如开启,需要同时填入 httpDNSServiceId 。 HttpDNS 用法详见 [移动解析HttpDNS](https://developers.weixin.qq.com/miniprogram/dev/framework/ability/HTTPDNS.html)
*/
enableHttpDNS?: boolean;
/**
* HttpDNS 服务商 Id。 HttpDNS 用法详见 [移动解析HttpDNS](https://developers.weixin.qq.com/miniprogram/dev/framework/ability/HTTPDNS.html)
*/
httpDNSServiceId?: 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;
}
+26
View File
@@ -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;
}
+61
View File
@@ -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;
}
+23
View File
@@ -0,0 +1,23 @@
declare namespace UniNamespace {
interface OnMemoryWarningCallbackResult {
/**
* 仅 Android 有该字段,对应系统内存告警等级宏定义
*/
level: number;
}
type OnMemoryWarningCallback = (res: OnMemoryWarningCallbackResult) => void;
}
interface Uni {
/**
* 监听内存不足告警事件。
*
* 文档: [https://uniapp.dcloud.net.cn/api/system/memory.html#onmemorywarning](https://uniapp.dcloud.net.cn/api/system/memory.html#onmemorywarning)
*/
onMemoryWarning(callback: UniNamespace.OnMemoryWarningCallback): void;
/**
* 取消监听内存不足告警事件。不传入 callback 则取消所有监听。
*
* 文档: [https://uniapp.dcloud.net.cn/api/system/memory.html#offmemorywarning](https://uniapp.dcloud.net.cn/api/system/memory.html#offmemorywarning)
*/
offMemoryWarning(callback?: UniNamespace.OnMemoryWarningCallback): void;
}
+18
View File
@@ -0,0 +1,18 @@
declare namespace UniNamespace {
type OnUserCaptureScreenCallback = (res?: { errMsg: string }) => void;
}
interface Uni {
/**
* 监听用户主动截屏事件,用户使用系统截屏按键截屏时触发此事件。
*
* 文档: [https://uniapp.dcloud.net.cn/api/system/capture-screen.html#onusercapturescreen](https://uniapp.dcloud.net.cn/api/system/capture-screen.html#onusercapturescreen)
*/
onUserCaptureScreen(callback: UniNamespace.OnUserCaptureScreenCallback): void;
/**
* 用户主动截屏事件。取消事件监听。
*
* 文档: [https://uniapp.dcloud.net.cn/api/system/capture-screen.html#offusercapturescreen](https://uniapp.dcloud.net.cn/api/system/capture-screen.html#offusercapturescreen)
*/
offUserCaptureScreen(callback: UniNamespace.OnUserCaptureScreenCallback): void;
}
+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;
}
+37
View File
@@ -0,0 +1,37 @@
declare namespace UniNamespace {
interface GetBatteryInfoSuccessCallbackResult {
/**
* 是否正在充电中
*/
isCharging: boolean;
/**
* 设备电量,范围 1 - 100
*/
level: number;
errMsg: string;
}
interface GetBatteryInfoOption {
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (result: any) => void;
/**
* 接口调用失败的回调函数
*/
fail?: (result: any) => void;
/**
* 接口调用成功的回调函数
*/
success?: (result: GetBatteryInfoSuccessCallbackResult) => void;
}
}
interface Uni {
/**
* 获取设备电量
*
* 文档: [https://uniapp.dcloud.net.cn/api/system/batteryInfo.html](https://uniapp.dcloud.net.cn/api/system/batteryInfo.html)
*/
getBatteryInfo(option?: UniNamespace.GetBatteryInfoOption): void;
}
+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.
+214
View File
@@ -0,0 +1,214 @@
'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 formatH5Log(type, filename, ...args) {
console[type].apply(console, [...args, filename]);
}
function resolveEasycom(component, easycom) {
return typeof component === 'string' ? easycom : component;
}
/// <reference types="@dcloudio/types" />
const createHook = (lifecycle) => (hook, target = vue.getCurrentInstance()) => {
// post-create lifecycle registrations are noops during SSR
!vue.isInSSRComponentSetup && vue.injectHook(lifecycle, hook, target);
};
const onShow = /*#__PURE__*/ createHook(uniShared.ON_SHOW);
const onHide = /*#__PURE__*/ createHook(uniShared.ON_HIDE);
const onLaunch =
/*#__PURE__*/ createHook(uniShared.ON_LAUNCH);
const onError =
/*#__PURE__*/ createHook(uniShared.ON_ERROR);
const onThemeChange =
/*#__PURE__*/ createHook(uniShared.ON_THEME_CHANGE);
const onPageNotFound =
/*#__PURE__*/ createHook(uniShared.ON_PAGE_NOT_FOUND);
const onUnhandledRejection = /*#__PURE__*/ createHook(uniShared.ON_UNHANDLE_REJECTION);
const onExit = /*#__PURE__*/ createHook(uniShared.ON_EXIT);
const onInit =
/*#__PURE__*/ createHook(uniShared.ON_INIT);
// 小程序如果想在 setup 的 props 传递页面参数,需要定义 props,故同时暴露 onLoad 吧
const onLoad =
/*#__PURE__*/ createHook(uniShared.ON_LOAD);
const onReady = /*#__PURE__*/ createHook(uniShared.ON_READY);
const onUnload = /*#__PURE__*/ createHook(uniShared.ON_UNLOAD);
const onResize =
/*#__PURE__*/ createHook(uniShared.ON_RESIZE);
const onBackPress =
/*#__PURE__*/ createHook(uniShared.ON_BACK_PRESS);
const onPageScroll =
/*#__PURE__*/ createHook(uniShared.ON_PAGE_SCROLL);
const onTabItemTap =
/*#__PURE__*/ createHook(uniShared.ON_TAB_ITEM_TAP);
const onReachBottom = /*#__PURE__*/ createHook(uniShared.ON_REACH_BOTTOM);
const onPullDownRefresh = /*#__PURE__*/ createHook(uniShared.ON_PULL_DOWN_REFRESH);
const onSaveExitState =
/*#__PURE__*/ createHook(uniShared.ON_SAVE_EXIT_STATE);
const onShareTimeline =
/*#__PURE__*/ createHook(uniShared.ON_SHARE_TIMELINE);
const onAddToFavorites =
/*#__PURE__*/ createHook(uniShared.ON_ADD_TO_FAVORITES);
const onShareAppMessage =
/*#__PURE__*/ createHook(uniShared.ON_SHARE_APP_MESSAGE);
const onNavigationBarButtonTap = /*#__PURE__*/ createHook(uniShared.ON_NAVIGATION_BAR_BUTTON_TAP);
const onNavigationBarSearchInputChanged = /*#__PURE__*/ createHook(uniShared.ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED);
const onNavigationBarSearchInputClicked = /*#__PURE__*/ createHook(uniShared.ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED);
const onNavigationBarSearchInputConfirmed = /*#__PURE__*/ createHook(uniShared.ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED);
const onNavigationBarSearchInputFocusChanged =
/*#__PURE__*/ createHook(uniShared.ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED);
// for uni-app-x web
const onPageHide = onHide;
const onPageShow = onShow;
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.formatH5Log = formatH5Log;
exports.getCurrentSubNVue = getCurrentSubNVue;
exports.getSsrGlobalData = getSsrGlobalData;
exports.onAddToFavorites = onAddToFavorites;
exports.onBackPress = onBackPress;
exports.onError = onError;
exports.onExit = onExit;
exports.onHide = onHide;
exports.onInit = onInit;
exports.onLaunch = onLaunch;
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.onShareTimeline = onShareTimeline;
exports.onShow = onShow;
exports.onTabItemTap = onTabItemTap;
exports.onThemeChange = onThemeChange;
exports.onUnhandledRejection = onUnhandledRejection;
exports.onUnload = onUnload;
exports.renderComponentSlot = renderComponentSlot;
exports.requireNativePlugin = requireNativePlugin;
exports.resolveEasycom = resolveEasycom;
exports.shallowSsrRef = shallowSsrRef;
exports.ssrRef = ssrRef;
+115
View File
@@ -0,0 +1,115 @@
/// <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 formatH5Log(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 { isPlainObject }
declare interface NavigationBarSearchInputFocusChanged {
focus: boolean;
}
export declare const onAddToFavorites: (hook: (options: Page.AddToFavoritesOption) => Page.CustomFavoritesContent, target?: ComponentInternalInstance | null) => void;
export declare const onBackPress: (hook: (options: Page.BackPressOption) => any, 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 onLaunch: (hook: (options?: App.LaunchShowOption | undefined) => void, 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: ((options?: App.LaunchShowOption | undefined) => void) | (() => 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 onShareTimeline: (hook: () => Page.ShareTimelineContent, target?: ComponentInternalInstance | null) => void;
export declare const onShow: (hook: ((options?: App.LaunchShowOption | undefined) => void) | (() => 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 onUnhandledRejection: (hook: (options: UniApp.OnUnhandledRejectionCallbackResult) => void, target?: ComponentInternalInstance | null) => void;
export declare const onUnload: (hook: () => any, 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 { }
+132
View File
@@ -0,0 +1,132 @@
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_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_SHARE_TIMELINE, ON_ADD_TO_FAVORITES, ON_SHARE_APP_MESSAGE, 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 formatH5Log(type, filename, ...args) {
console[type].apply(console, [...args, filename]);
}
function resolveEasycom(component, easycom) {
return typeof component === 'string' ? easycom : component;
}
/// <reference types="@dcloudio/types" />
const createHook = (lifecycle) => (hook, target = getCurrentInstance()) => {
// post-create lifecycle registrations are noops during SSR
!isInSSRComponentSetup && injectHook(lifecycle, hook, target);
};
const onShow = /*#__PURE__*/ createHook(ON_SHOW);
const onHide = /*#__PURE__*/ createHook(ON_HIDE);
const onLaunch =
/*#__PURE__*/ createHook(ON_LAUNCH);
const onError =
/*#__PURE__*/ createHook(ON_ERROR);
const onThemeChange =
/*#__PURE__*/ createHook(ON_THEME_CHANGE);
const onPageNotFound =
/*#__PURE__*/ createHook(ON_PAGE_NOT_FOUND);
const onUnhandledRejection = /*#__PURE__*/ createHook(ON_UNHANDLE_REJECTION);
const onExit = /*#__PURE__*/ createHook(ON_EXIT);
const onInit =
/*#__PURE__*/ createHook(ON_INIT);
// 小程序如果想在 setup 的 props 传递页面参数,需要定义 props,故同时暴露 onLoad 吧
const onLoad =
/*#__PURE__*/ createHook(ON_LOAD);
const onReady = /*#__PURE__*/ createHook(ON_READY);
const onUnload = /*#__PURE__*/ createHook(ON_UNLOAD);
const onResize =
/*#__PURE__*/ createHook(ON_RESIZE);
const onBackPress =
/*#__PURE__*/ createHook(ON_BACK_PRESS);
const onPageScroll =
/*#__PURE__*/ createHook(ON_PAGE_SCROLL);
const onTabItemTap =
/*#__PURE__*/ createHook(ON_TAB_ITEM_TAP);
const onReachBottom = /*#__PURE__*/ createHook(ON_REACH_BOTTOM);
const onPullDownRefresh = /*#__PURE__*/ createHook(ON_PULL_DOWN_REFRESH);
const onSaveExitState =
/*#__PURE__*/ createHook(ON_SAVE_EXIT_STATE);
const onShareTimeline =
/*#__PURE__*/ createHook(ON_SHARE_TIMELINE);
const onAddToFavorites =
/*#__PURE__*/ createHook(ON_ADD_TO_FAVORITES);
const onShareAppMessage =
/*#__PURE__*/ createHook(ON_SHARE_APP_MESSAGE);
const onNavigationBarButtonTap = /*#__PURE__*/ createHook(ON_NAVIGATION_BAR_BUTTON_TAP);
const onNavigationBarSearchInputChanged = /*#__PURE__*/ createHook(ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED);
const onNavigationBarSearchInputClicked = /*#__PURE__*/ createHook(ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED);
const onNavigationBarSearchInputConfirmed = /*#__PURE__*/ createHook(ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED);
const onNavigationBarSearchInputFocusChanged =
/*#__PURE__*/ createHook(ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED);
// for uni-app-x web
const onPageHide = onHide;
const onPageShow = onShow;
function renderComponentSlot(slots, name, props = null) {
if (slots[name]) {
return slots[name](props);
}
return null;
}
export { formatAppLog, formatH5Log, getCurrentSubNVue, getSsrGlobalData, onAddToFavorites, onBackPress, onError, onExit, onHide, onInit, onLaunch, onLoad, onNavigationBarButtonTap, onNavigationBarSearchInputChanged, onNavigationBarSearchInputClicked, onNavigationBarSearchInputConfirmed, onNavigationBarSearchInputFocusChanged, onPageHide, onPageNotFound, onPageScroll, onPageShow, onPullDownRefresh, onReachBottom, onReady, onResize, onSaveExitState, onShareAppMessage, onShareTimeline, onShow, onTabItemTap, onThemeChange, onUnhandledRejection, onUnload, renderComponentSlot, requireNativePlugin, resolveEasycom, shallowSsrRef, ssrRef };
+12
View File
@@ -0,0 +1,12 @@
'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')(),
];
module.exports = index;
+38
View File
@@ -0,0 +1,38 @@
{
"name": "@dcloudio/uni-app",
"version": "3.0.0-4020420240722001",
"description": "@dcloudio/uni-app",
"main": "./dist/uni-app.cjs.js",
"module": "./dist/uni-app.es.js",
"types": "./dist/uni-app.d.ts",
"files": [
"dist"
],
"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": {
"@dcloudio/uni-cloud": "3.0.0-4020420240722001",
"@dcloudio/uni-components": "3.0.0-4020420240722001",
"@dcloudio/uni-i18n": "3.0.0-4020420240722001",
"@dcloudio/uni-push": "3.0.0-4020420240722001",
"@dcloudio/uni-shared": "3.0.0-4020420240722001",
"@dcloudio/uni-stat": "3.0.0-4020420240722001",
"@vue/shared": "3.4.21"
},
"peerDependencies": {
"@dcloudio/types": "^3.4.8"
}
}
+1
View File
@@ -0,0 +1 @@
"use strict";var t=require("./index.js");const n=new t.Automator;let s,i=!1;try{s=require("jest-environment-node")}catch(t){s=require(require.resolve("jest-environment-node",{paths:[process.cwd()]}))}s&&s.TestEnvironment&&(i=!0,s=s.TestEnvironment);module.exports=class extends s{constructor(t,n){var s,o;super(i?{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,(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})}async setup(){await super.setup();const s=global;if(s.__init__){if(!s.program)throw Error("Program init failed")}else s.__init__=!0,this.launchOptions.platform=this.launchOptions.platform||process.env.UNI_PLATFORM,s.program=await n.launch(this.launchOptions),this.launchOptions.devtools&&this.launchOptions.devtools.remote&&await s.program.remote(!0);this.global.program=s.program,this.global.uni=t.initUni(s.program)}async teardown(){await super.teardown()}};
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
"use strict";module.exports=async function(){const o=global.program;o&&o.teardown(),await new Promise((o=>{setTimeout((()=>{o(void 0)}),3e3)}))};
+35
View File
@@ -0,0 +1,35 @@
<script>
let firstBackTime = 0
export default {
onLaunch: function () {
console.log('App Launch')
},
onShow: function () {
console.log('App Show')
},
onHide: function () {
console.log('App Hide')
},
// #ifdef APP-ANDROID
onLastPageBackPress: function () {
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: function () {
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,8 @@
{
"name" : "NAME",
"appid" : "APPID",
"description" : "",
"versionName" : "1.0.0",
"versionCode" : "100",
"uni-app-x" : {}
}
@@ -0,0 +1,14 @@
{
"pages": [
{
"path": "pages/index/index",
"style": {
"navigationBarTitleText": "uni-app x"
}
}
],
"globalStyle": {
"navigationStyle": "custom",
"pageOrientation": "auto"
}
}
@@ -0,0 +1,115 @@
<template>
<view style="flex: 1;">
<!-- #ifdef APP-ANDROID -->
<view :style="{ height: `${statusBarHeight}px` }"></view>
<!-- #endif -->
<web-view
ref="webview"
id="webview"
style="flex: 1;"
:webview-styles="webviewStyles"
:src="src"
@message="message"
@error="error"
/>
</view>
</template>
<script lang='uts'>
export default {
data() {
return {
src: process.env.UNI_AUTOMATOR_APP_WEBVIEW_SRC,
webviewElement: null as UniWebViewElement | null,
webviewContext: null as WebviewContext | null,
webviewStyles: {
progress: false
},
statusBarHeight: 0,
safeAreaTop: 0
}
},
onReady() {
const windowInfo = uni.getWindowInfo()
this.statusBarHeight = windowInfo.statusBarHeight
this.safeAreaTop = windowInfo.safeAreaInsets.top
this.webviewElement = this.$refs['webview'] as UniWebViewElement
this.webviewContext = uni.createWebviewContext('webview', this)
},
methods: {
initAutomator() {
const options = {
wsEndpoint: process.env.UNI_AUTOMATOR_WS_ENDPOINT
}
this.webviewContext!.evalJS(`initRuntimeAutomator(${JSON.stringify(options)})`)
console.log('initRuntimeAutomator...')
},
message(msg: UniWebViewMessageEvent) {
// #ifdef APP-ANDROID
// data 由 对象变更成数组
const data = msg.detail.data[0];
const id = data.get("id") as number
const type = data.get("type") as string
const dataObj = data.get("data") as UTSJSONObject
const action = dataObj.getString("action")!
const args = dataObj.get("args")
// #endif
// #ifndef APP-ANDROID
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') {
this.initAutomator()
} else {
console.log(id, action, args)
if (action == 'captureScreenshot') {
// 调用截图
this.$viewToTempFilePath({
id: 'webview',
// #ifdef APP-ANDROID
offsetY: `44`,
// #endif
// #ifndef APP-ANDROID
offsetY: `${this.safeAreaTop + 44}`,
// #endif
overwrite: true,
wholeContent: true,
success: (res) => {
const fileManager = uni.getFileSystemManager()
fileManager.readFile({
encoding: 'base64',
filePath: res.tempFilePath,
success: (readFileRes) => {
this.callback(id, { data: readFileRes.data }, '')
},
fail: (error) => {
this.callback(id, '', error.errMsg)
},
} as ReadFileOptions)
},
fail: (res) => {
this.callback(id, '', res.errMsg)
}
})
}
}
},
error(event : WebViewErrorEvent) {
console.log('webview load error', JSON.stringify(event.detail));
},
callback(id : number, res : any | null, error : string) {
this.webviewContext!.evalJS(`onPostMessageFromUniXWebView(${id},${JSON.stringify(res)},${JSON.stringify(error)})`)
}
}
}
</script>
+63
View File
@@ -0,0 +1,63 @@
"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' && 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') {
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') {
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,
};
}
},
};
}),
];
+52
View File
@@ -0,0 +1,52 @@
{
"name": "@dcloudio/uni-automator",
"version": "3.0.0-4020420240722001",
"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"
],
"uvue": true
},
"gitHead": "33e807d66e1fe47e2ee08ad9c59247e37b8884da",
"dependencies": {
"@dcloudio/uni-cli-shared": "3.0.0-4020420240722001",
"address": "^1.1.2",
"cross-env": "^7.0.3",
"debug": "^4.3.3",
"default-gateway": "^6.0.3",
"fs-extra": "^10.0.0",
"jsonc-parser": "^3.2.0",
"licia": "^1.29.0",
"merge": "^2.1.1",
"qrcode-reader": "^1.0.4",
"qrcode-terminal": "^0.12.0",
"ws": "^8.4.2"
},
"devDependencies": {
"@types/debug": "^4.1.7",
"@types/fs-extra": "^9.0.13"
},
"peerDependencies": {
"jest": "27.0.4",
"jest-environment-node": "27.5.1"
}
}
+3
View File
@@ -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;
+37
View File
@@ -0,0 +1,37 @@
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 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 COMMON_EXCLUDE: RegExp[];
export declare const KNOWN_ASSET_TYPES: string[];
export declare const DEFAULT_ASSETS_RE: RegExp;
export declare const TEXT_STYLE: string[];
+86
View File
@@ -0,0 +1,86 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TEXT_STYLE = exports.DEFAULT_ASSETS_RE = exports.KNOWN_ASSET_TYPES = exports.COMMON_EXCLUDE = 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.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?$/;
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.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'];
+21
View File
@@ -0,0 +1,21 @@
export declare const API_DEPS_CSS: {
showModal: string[];
showToast: string[];
showActionSheet: string[];
previewImage: string[];
openLocation: string[];
chooseLocation: string[];
};
export declare const COMPONENT_DEPS_CSS: {
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[];
};
+42
View File
@@ -0,0 +1,42 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.COMPONENT_DEPS_CSS = exports.API_DEPS_CSS = void 0;
const constants_1 = require("./constants");
const RESIZE_SENSOR_CSS = constants_1.BASE_COMPONENTS_STYLE_PATH + 'resize-sensor.css';
const REFRESHER_CSS = constants_1.BASE_COMPONENTS_STYLE_PATH + 'refresher.css';
exports.API_DEPS_CSS = {
showModal: [`${constants_1.H5_API_STYLE_PATH}modal.css`],
showToast: [`${constants_1.H5_API_STYLE_PATH}toast.css`],
showActionSheet: [`${constants_1.H5_API_STYLE_PATH}action-sheet.css`],
previewImage: [
RESIZE_SENSOR_CSS,
`${constants_1.BASE_COMPONENTS_STYLE_PATH}swiper.css`,
`${constants_1.BASE_COMPONENTS_STYLE_PATH}swiper-item.css`,
`${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: [
`${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`,
],
};
exports.COMPONENT_DEPS_CSS = {
canvas: [RESIZE_SENSOR_CSS],
image: [RESIZE_SENSOR_CSS],
'movable-area': [RESIZE_SENSOR_CSS],
'picker-view': [RESIZE_SENSOR_CSS],
'picker-view-column': [RESIZE_SENSOR_CSS],
'rich-text': [RESIZE_SENSOR_CSS],
textarea: [RESIZE_SENSOR_CSS],
'web-view': [RESIZE_SENSOR_CSS],
picker: [
RESIZE_SENSOR_CSS,
`${constants_1.BASE_COMPONENTS_STYLE_PATH}picker-view.css`,
`${constants_1.BASE_COMPONENTS_STYLE_PATH}picker-view-column.css`,
],
'scroll-view': [REFRESHER_CSS],
'list-view': [RESIZE_SENSOR_CSS, REFRESHER_CSS],
};
+36
View File
@@ -0,0 +1,36 @@
interface EasycomOption {
isX?: boolean;
dirs?: string[];
rootDir: string;
extensions: string[];
autoscan?: boolean;
custom?: EasycomCustom;
}
export interface EasycomMatcher {
name: string;
pattern: RegExp;
replacement: string;
}
interface EasycomCustom {
[key: string]: string;
}
export declare function initEasycoms(inputDir: string, { dirs, platform, isX, }: {
dirs: string[];
platform: UniApp.PLATFORM;
isX?: boolean;
}): {
options: 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 {};
+305
View File
@@ -0,0 +1,305 @@
"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 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 = {
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 options = 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);
}
};
initEasycom(options);
initUTSEasycom();
const componentExtNames = isX ? 'uvue|vue' : 'vue';
const res = {
options,
filter: (0, pluginutils_1.createFilter)([
'components/*/*.(' + componentExtNames + '|jsx|tsx)',
'uni_modules/*/components/*/*.(' + componentExtNames + '|jsx|tsx)',
'utssdk/*/**/*.(' + componentExtNames + ')',
'uni_modules/*/utssdk/*/*.(' + componentExtNames + ')',
], [], {
resolve: inputDir,
}),
refresh() {
res.options = initEasycomOptions();
initEasycom(res.options);
initUTSEasycom();
},
easycoms,
};
return res;
}
exports.initEasycoms = initEasycoms;
exports.initEasycomsOnce = (0, uni_shared_1.once)(initEasycoms);
function initUniModulesEasycomDirs(uniModulesDir) {
if (!fs_1.default.existsSync(uniModulesDir)) {
return [];
}
return fs_1.default
.readdirSync(uniModulesDir)
.map((uniModuleDir) => {
const uniModuleComponentsDir = path_1.default.resolve(uniModulesDir, uniModuleDir, 'components');
if (fs_1.default.existsSync(uniModuleComponentsDir)) {
return uniModuleComponentsDir;
}
})
.filter(Boolean);
}
function initEasycom({ isX, dirs, rootDir, custom, extensions, }) {
clearEasycom();
rootDir = (0, utils_1.normalizePath)(rootDir);
const easycomsObj = Object.create(null);
if (dirs && dirs.length && rootDir) {
const autoEasyComObj = initAutoScanEasycoms(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));
}
let imported = '';
// 加密插件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)}`;
imported = genUTSComponentPublicInstanceImported(rootDir, `@/uni_modules/${moduleId}/components/${tagName}/${tagName}`);
}
else {
imported = genUTSComponentPublicInstanceImported(rootDir, source);
}
addUTSEasyComAutoImports(source, [
imported,
genUTSComponentPublicInstanceIdent(tagName),
]);
});
}
(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;
}
source = tag.replace(matcher.pattern, matcher.replacement);
easycomsCache.set(tag, source);
debugEasycom('matchEasycom', tag, source);
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(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 is_uni_modules = path_1.default.basename(path_1.default.resolve(dir, '../..')) === 'uni_modules';
const is_encrypt_uni_modules = // uni_modules模式不需要此逻辑
process.env.UNI_COMPILE_TARGET !== 'uni_modules' &&
is_uni_modules &&
fs_1.default.existsSync(path_1.default.resolve(dir, '../encrypt'));
const uni_modules_plugin_id = is_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;
}
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}$`] = is_encrypt_uni_modules
? (0, utils_1.normalizePath)(path_1.default.join(rootDir, `uni_modules/${uni_modules_plugin_id}?${
// android 走 proxy
process.env.UNI_APP_X === 'true' &&
process.env.UNI_UTS_PLATFORM === 'app-android'
? 'uts-proxy'
: 'uni_helpers'}`))
: `${importDir}/${name}${ext}`;
break;
}
}
});
return easycoms;
}
function initAutoScanEasycoms(dirs, rootDir, extensions) {
const conflict = {};
const res = dirs.reduce((easycoms, dir) => {
const curEasycoms = initAutoScanEasycom(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) {
return `import { ${imported} as ${local} } from '${source}';`;
}
return `import ${local} from '${source}';`;
}
const RESOLVE_EASYCOM_IMPORT_CODE = `import { resolveDynamicComponent as __resolveDynamicComponent } from 'vue';import { resolveEasycom } from '@dcloudio/uni-app';`;
function genResolveEasycomCode(importDeclarations, code, name) {
if (!importDeclarations.includes(RESOLVE_EASYCOM_IMPORT_CODE)) {
importDeclarations.push(RESOLVE_EASYCOM_IMPORT_CODE);
}
return `resolveEasycom(${code.replace('_resolveComponent', '__resolveDynamicComponent')}, ${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;
+20
View File
@@ -0,0 +1,20 @@
export declare function initDefine(stringifyBoolean?: 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;
};
+51
View File
@@ -0,0 +1,51 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initDefine = void 0;
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;
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),
};
}
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;
}, {});
}
+2
View File
@@ -0,0 +1,2 @@
export { initDefine } from './define';
export { initAppProvide, initH5Provide } from './provide';
+8
View File
@@ -0,0 +1,8 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initH5Provide = 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; } });
Object.defineProperty(exports, "initH5Provide", { enumerable: true, get: function () { return provide_1.initH5Provide; } });
+11
View File
@@ -0,0 +1,11 @@
export declare function initAppProvide(): {
__f__: string[];
crypto: string[];
'window.crypto': string[];
'global.crypto': string[];
'uni.getCurrentSubNVue': string[];
'uni.requireNativePlugin': string[];
};
export declare function initH5Provide(): {
__f__: string[];
};
+26
View File
@@ -0,0 +1,26 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.initH5Provide = exports.initAppProvide = void 0;
const path_1 = __importDefault(require("path"));
const libDir = path_1.default.resolve(__dirname, '../../lib');
function initAppProvide() {
const cryptoDefine = [path_1.default.join(libDir, 'crypto.js'), 'default'];
return {
__f__: ['@dcloudio/uni-app', 'formatAppLog'],
crypto: cryptoDefine,
'window.crypto': cryptoDefine,
'global.crypto': cryptoDefine,
'uni.getCurrentSubNVue': ['@dcloudio/uni-app', 'getCurrentSubNVue'],
'uni.requireNativePlugin': ['@dcloudio/uni-app', 'requireNativePlugin'],
};
}
exports.initAppProvide = initAppProvide;
function initH5Provide() {
return {
__f__: ['@dcloudio/uni-app', 'formatH5Log'],
};
}
exports.initH5Provide = initH5Provide;
+3
View File
@@ -0,0 +1,3 @@
import type { BuildOptions } from 'esbuild';
export declare function transformWithEsbuild(code: string, filename: string, options: BuildOptions): Promise<import("esbuild").BuildResult<BuildOptions>>;
export declare function esbuild(options: BuildOptions): Promise<import("esbuild").BuildResult<BuildOptions>>;
+46
View File
@@ -0,0 +1,46 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.esbuild = exports.transformWithEsbuild = void 0;
const path_1 = __importDefault(require("path"));
function transformWithEsbuild(code, filename, options) {
options.stdin = {
contents: code,
resolveDir: path_1.default.dirname(filename),
};
return Promise.resolve().then(() => __importStar(require('esbuild'))).then((esbuild) => {
return esbuild.build(options);
});
}
exports.transformWithEsbuild = transformWithEsbuild;
function esbuild(options) {
return Promise.resolve().then(() => __importStar(require('esbuild'))).then((esbuild) => {
return esbuild.build(options);
});
}
exports.esbuild = esbuild;
+1
View File
@@ -0,0 +1 @@
export { default as chokidar } from 'chokidar';
+8
View File
@@ -0,0 +1,8 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.chokidar = void 0;
var chokidar_1 = require("chokidar");
Object.defineProperty(exports, "chokidar", { enumerable: true, get: function () { return __importDefault(chokidar_1).default; } });
+16
View File
@@ -0,0 +1,16 @@
export declare function isWxs(id: string): boolean;
export declare function isSjs(id: string): boolean;
export declare function isRenderjs(id: string): boolean;
type FilterType = 'wxs' | 'renderjs' | 'sjs';
export declare function parseRenderjs(id: string): {
type: FilterType;
name: string;
filename: string;
} | {
readonly type: "";
readonly name: "";
readonly filename: "";
};
export declare function missingModuleName(type: FilterType, code: string): string;
export declare function parseFilterNames(lang: string, code: string): string[];
export {};
+60
View File
@@ -0,0 +1,60 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseFilterNames = exports.missingModuleName = exports.parseRenderjs = exports.isRenderjs = exports.isSjs = exports.isWxs = void 0;
const url_1 = require("./vite/utils/url");
const WXS_RE = /vue&type=wxs/;
function isWxs(id) {
return WXS_RE.test(id);
}
exports.isWxs = isWxs;
const SJS_RE = /vue&type=sjs/;
function isSjs(id) {
return SJS_RE.test(id);
}
exports.isSjs = isSjs;
const RENDERJS_RE = /vue&type=renderjs/;
function isRenderjs(id) {
return RENDERJS_RE.test(id);
}
exports.isRenderjs = isRenderjs;
function parseRenderjs(id) {
if (isWxs(id) || isRenderjs(id) || isSjs(id)) {
const { query, filename } = (0, url_1.parseVueRequest)(id);
return {
type: query.type,
name: query.name,
filename,
};
}
return {
type: '',
name: '',
filename: '',
};
}
exports.parseRenderjs = parseRenderjs;
function missingModuleName(type, code) {
return `<script module="missing module name" lang="${type}">
${code}
</script>`;
}
exports.missingModuleName = missingModuleName;
const moduleRE = /module=["'](.*?)["']/;
function parseFilterNames(lang, code) {
const names = [];
const scriptTags = code.match(/<script\b[^>]*>/gm);
if (!scriptTags) {
return names;
}
const langRE = new RegExp(`lang=["']${lang}["']`);
scriptTags.forEach((scriptTag) => {
if (langRE.test(scriptTag)) {
const matches = scriptTag.match(moduleRE);
if (matches) {
names.push(matches[1]);
}
}
});
return names;
}
exports.parseFilterNames = parseFilterNames;
+1
View File
@@ -0,0 +1 @@
export declare function emptyDir(dir: string, skip?: string[]): void;
+21
View File
@@ -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.emptyDir = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
function emptyDir(dir, skip = []) {
try {
for (const file of fs_1.default.readdirSync(dir)) {
if (skip.includes(file)) {
continue;
}
// node >= 14.14.0
fs_1.default.rmSync(path_1.default.resolve(dir, file), { recursive: true, force: true });
}
}
catch (e) { }
}
exports.emptyDir = emptyDir;
+5
View File
@@ -0,0 +1,5 @@
import type { Formatter } from '../logs/format';
export declare function initModuleAlias(): void;
export declare function installHBuilderXPlugin(plugin: string): void;
export declare const moduleAliasFormatter: Formatter;
export declare function formatInstallHBuilderXPluginTips(lang: string, preprocessor: string): string;
+143
View File
@@ -0,0 +1,143 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.formatInstallHBuilderXPluginTips = exports.moduleAliasFormatter = exports.installHBuilderXPlugin = exports.initModuleAlias = void 0;
const path_1 = __importDefault(require("path"));
const module_alias_1 = __importDefault(require("module-alias"));
const env_1 = require("./env");
const hbxPlugins = {
typescript: 'compile-typescript/node_modules/typescript',
less: 'compile-less/node_modules/less',
sass: 'compile-dart-sass/node_modules/sass',
stylus: 'compile-stylus/node_modules/stylus',
pug: 'compile-pug-cli/node_modules/pug',
};
function initModuleAlias() {
const compilerSfcPath = path_1.default.resolve(__dirname, '../../lib/@vue/compiler-sfc');
const serverRendererPath = require.resolve('@vue/server-renderer');
module_alias_1.default.addAliases({
'@vue/shared': require.resolve('@vue/shared'),
'@vue/shared/dist/shared.esm-bundler.js': require.resolve('@vue/shared/dist/shared.esm-bundler.js'),
'@vue/compiler-dom': require.resolve('@vue/compiler-dom'),
'@vue/compiler-sfc': compilerSfcPath,
'@vue/server-renderer': serverRendererPath,
'vue/compiler-sfc': compilerSfcPath,
'vue/server-renderer': serverRendererPath,
});
if (process.env.VITEST) {
module_alias_1.default.addAliases({
vue: '@dcloudio/uni-h5-vue',
'vue/package.json': '@dcloudio/uni-h5-vue/package.json',
});
}
if ((0, env_1.isInHBuilderX)()) {
// 又是为了复用 HBuilderX 的插件逻辑,硬编码映射
Object.keys(hbxPlugins).forEach((lang) => {
const realPath = path_1.default.resolve(process.env.UNI_HBUILDERX_PLUGINS, hbxPlugins[lang]);
module_alias_1.default.addAlias(lang,
// @ts-expect-error
() => {
try {
require.resolve(realPath);
}
catch (e) {
const msg = exports.moduleAliasFormatter.format(`Preprocessor dependency "${lang}" not found. Did you install it?`);
console.error(msg);
process.exit(0);
}
return realPath;
});
});
// web 平台用了 vite 内置 css 插件,该插件会加载预编译器如scss、less等,需要转向到 HBuilderX 的对应编译器插件
if (process.env.UNI_PLATFORM === 'h5' ||
process.env.UNI_PLATFORM === 'web') {
// https://github.com/vitejs/vite/blob/main/packages/vite/src/node/packages.ts#L92
// 拦截预编译器
const join = path_1.default.join;
path_1.default.join = function (...paths) {
if (paths.length === 4) {
// path.join(basedir, 'node_modules', pkgName, 'package.json')
// const basedir = paths[0]
const nodeModules = paths[1]; // = node_modules
const pkgName = paths[2];
const packageJson = paths[3]; // = package.json
if (nodeModules === 'node_modules' &&
packageJson === 'package.json' &&
hbxPlugins[pkgName]) {
return path_1.default.resolve(process.env.UNI_HBUILDERX_PLUGINS, hbxPlugins[pkgName], packageJson);
}
}
return join(...paths);
};
// https://github.com/vitejs/vite/blob/892916d040a035edde1add93c192e0b0c5c9dd86/packages/vite/src/node/plugins/css.ts#L1481
// const oldSync = resovle.sync
// resovle.sync = (id: string, opts?: SyncOpts) => {
// if ((hbxPlugins as any)[id]) {
// return path.resolve(
// process.env.UNI_HBUILDERX_PLUGINS,
// hbxPlugins[id as keyof typeof hbxPlugins]
// )
// }
// return oldSync(id, opts)
// }
}
}
}
exports.initModuleAlias = initModuleAlias;
function supportAutoInstallPlugin() {
return !!process.env.HX_Version;
}
function installHBuilderXPlugin(plugin) {
if (!supportAutoInstallPlugin()) {
return;
}
return console.error(`%HXRunUniAPPPluginName%${plugin}%HXRunUniAPPPluginName%`);
}
exports.installHBuilderXPlugin = installHBuilderXPlugin;
const installPreprocessorTips = {};
exports.moduleAliasFormatter = {
test(msg) {
return msg.includes('Preprocessor dependency');
},
format(msg) {
let lang = '';
let preprocessor = '';
if (msg.includes(`"pug"`)) {
lang = 'pug';
preprocessor = 'compile-pug-cli';
}
else if (msg.includes(`"sass"`)) {
lang = 'sass';
preprocessor = 'compile-dart-sass';
}
else if (msg.includes(`"less"`)) {
lang = 'less';
preprocessor = 'compile-less';
}
else if (msg.includes('"stylus"')) {
lang = 'stylus';
preprocessor = 'compile-stylus';
}
else if (msg.includes('"typescript"')) {
lang = 'typescript';
preprocessor = 'compile-typescript';
}
if (lang) {
// 仅提醒一次
if (installPreprocessorTips[lang]) {
return '';
}
installPreprocessorTips[lang] = true;
installHBuilderXPlugin(preprocessor);
return formatInstallHBuilderXPluginTips(lang, preprocessor);
}
return msg;
},
};
function formatInstallHBuilderXPluginTips(lang, preprocessor) {
return `预编译器错误:代码使用了${lang}语言,但未安装相应的编译器插件,${supportAutoInstallPlugin() ? '正在从' : '请前往'}插件市场安装该插件:
https://ext.dcloud.net.cn/plugin?name=${preprocessor}`;
}
exports.formatInstallHBuilderXPluginTips = formatInstallHBuilderXPluginTips;
+7
View File
@@ -0,0 +1,7 @@
export declare const isInHBuilderX: () => boolean;
export declare const runByHBuilderX: () => boolean;
/**
* 增加 node_modules
*/
export declare function initModulePaths(): void;
export declare function fixBinaryPath(): void;
+79
View File
@@ -0,0 +1,79 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.fixBinaryPath = exports.initModulePaths = exports.runByHBuilderX = exports.isInHBuilderX = void 0;
const path_1 = __importDefault(require("path"));
const module_1 = __importDefault(require("module"));
const uni_shared_1 = require("@dcloudio/uni-shared");
const resolve_1 = require("../resolve");
const utils_1 = require("../utils");
exports.isInHBuilderX = (0, uni_shared_1.once)(() => {
// 自动化测试传入了 HX_APP_ROOT(其实就是UNI_HBUILDERX_PLUGINS)
if (process.env.HX_APP_ROOT) {
process.env.UNI_HBUILDERX_PLUGINS = process.env.HX_APP_ROOT + '/plugins';
return true;
}
try {
const { name } = require(path_1.default.resolve(process.cwd(), '../about/package.json'));
if (name === 'about') {
process.env.UNI_HBUILDERX_PLUGINS = path_1.default.resolve(process.cwd(), '..');
return true;
}
}
catch (e) {
// console.error(e)
}
return false;
});
exports.runByHBuilderX = (0, uni_shared_1.once)(() => {
return (!!process.env.UNI_HBUILDERX_PLUGINS &&
(!!process.env.RUN_BY_HBUILDERX || !!process.env.HX_Version));
});
/**
* 增加 node_modules
*/
function initModulePaths() {
if (!(0, exports.isInHBuilderX)()) {
return;
}
const Module = module.constructor.length > 1 ? module.constructor : module_1.default;
const nodeModulesPath = path_1.default.resolve(process.env.UNI_CLI_CONTEXT, 'node_modules');
const oldNodeModulePaths = Module._nodeModulePaths;
Module._nodeModulePaths = function (from) {
const paths = oldNodeModulePaths.call(this, from);
if (!paths.includes(nodeModulesPath)) {
paths.push(nodeModulesPath);
}
return paths;
};
}
exports.initModulePaths = initModulePaths;
function resolveEsbuildModule(name) {
try {
return path_1.default.dirname(require.resolve(name + '/package.json', {
paths: [path_1.default.dirname((0, resolve_1.resolveBuiltIn)('esbuild/package.json'))],
}));
}
catch (e) { }
return '';
}
function fixBinaryPath() {
// cli 工程在 HBuilderX 中运行
if (!(0, exports.isInHBuilderX)() && (0, exports.runByHBuilderX)()) {
if (utils_1.isWindows) {
const win64 = resolveEsbuildModule('esbuild-windows-64');
if (win64) {
process.env.ESBUILD_BINARY_PATH = path_1.default.join(win64, 'esbuild.exe');
}
}
else {
const arm64 = resolveEsbuildModule('esbuild-darwin-arm64');
if (arm64) {
process.env.ESBUILD_BINARY_PATH = path_1.default.join(arm64, 'bin/esbuild');
}
}
}
}
exports.fixBinaryPath = fixBinaryPath;
+4
View File
@@ -0,0 +1,4 @@
export { formatAtFilename } from './log';
export * from './env';
export { initModuleAlias, installHBuilderXPlugin, formatInstallHBuilderXPluginTips, } from './alias';
export declare function uniHBuilderXConsolePlugin(method?: string): import("vite").Plugin<any>;
+43
View File
@@ -0,0 +1,43 @@
"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);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniHBuilderXConsolePlugin = exports.formatInstallHBuilderXPluginTips = exports.installHBuilderXPlugin = exports.initModuleAlias = exports.formatAtFilename = void 0;
const path_1 = __importDefault(require("path"));
const utils_1 = require("../utils");
const console_1 = require("../vite/plugins/console");
var log_1 = require("./log");
Object.defineProperty(exports, "formatAtFilename", { enumerable: true, get: function () { return log_1.formatAtFilename; } });
__exportStar(require("./env"), exports);
var alias_1 = require("./alias");
Object.defineProperty(exports, "initModuleAlias", { enumerable: true, get: function () { return alias_1.initModuleAlias; } });
Object.defineProperty(exports, "installHBuilderXPlugin", { enumerable: true, get: function () { return alias_1.installHBuilderXPlugin; } });
Object.defineProperty(exports, "formatInstallHBuilderXPluginTips", { enumerable: true, get: function () { return alias_1.formatInstallHBuilderXPluginTips; } });
function uniHBuilderXConsolePlugin(method = '__f__') {
return (0, console_1.uniConsolePlugin)({
method,
filename(filename) {
filename = path_1.default.relative(process.env.UNI_INPUT_DIR, filename);
if (filename.startsWith('.') || path_1.default.isAbsolute(filename)) {
return '';
}
return (0, utils_1.normalizePath)(filename);
},
});
}
exports.uniHBuilderXConsolePlugin = uniHBuilderXConsolePlugin;
+7
View File
@@ -0,0 +1,7 @@
import type { LogErrorOptions } from 'vite';
import type { Formatter } from '../logs/format';
export declare function formatAtFilename(filename: string, line?: number, column?: number): string;
export declare const h5ServeFormatter: Formatter;
export declare const removeInfoFormatter: Formatter;
export declare const removeWarnFormatter: Formatter;
export declare const errorFormatter: Formatter<LogErrorOptions>;
+165
View File
@@ -0,0 +1,165 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.errorFormatter = exports.removeWarnFormatter = exports.removeInfoFormatter = exports.h5ServeFormatter = exports.formatAtFilename = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const picocolors_1 = __importDefault(require("picocolors"));
const compiler_core_1 = require("@vue/compiler-core");
const shared_1 = require("@vue/shared");
const utils_1 = require("../utils");
const constants_1 = require("../constants");
const ast_1 = require("../vite/utils/ast");
const utils_2 = require("../vite/plugins/vitejs/utils");
const SIGNAL_H5_LOCAL = ' ➜ Local:';
const SIGNAL_H5_NETWORK = ' ➜ Network:';
const networkLogs = [];
const ZERO_WIDTH_CHAR = {
NOTE: '',
WARNING: '\u200B',
ERROR: '\u200C',
backup0: '\u200D',
backup1: '\u200E',
backup2: '\u200F',
backup3: '\uFEFF',
};
function overridedConsole(name, oldFn, char) {
console[name] = function (...args) {
oldFn.apply(this, args.map((arg) => {
let item;
if (typeof arg !== 'object') {
item = `${char}${arg}${char}`;
}
else {
item = `${char}${JSON.stringify(arg)}${char}`;
}
return item;
}));
};
}
if (typeof console !== 'undefined') {
overridedConsole('warn', console.log, ZERO_WIDTH_CHAR.WARNING);
// overridedConsole('error', console.error, ZERO_WIDTH_CHAR.ERROR)
}
function formatAtFilename(filename, line, column) {
const file = path_1.default.relative(process.env.UNI_INPUT_DIR, filename.replace('\x00', '').split('?')[0]);
return `at ${picocolors_1.default.cyan((0, utils_1.normalizePath)(file === 'pages-json-uts' ? 'pages.json' : file) +
':' +
(line || 1) +
':' +
(column || 0))}`;
}
exports.formatAtFilename = formatAtFilename;
exports.h5ServeFormatter = {
test(msg) {
return msg.includes(SIGNAL_H5_LOCAL) || msg.includes(SIGNAL_H5_NETWORK);
},
format(msg) {
if (msg.includes(SIGNAL_H5_NETWORK)) {
networkLogs.push(msg.replace('➜ ', '*'));
process.nextTick(() => {
if (networkLogs.length) {
// 延迟打印所有 network,仅最后一个 network 替换 ➜ 为 -,通知 hbx
const len = networkLogs.length - 1;
networkLogs[len] = networkLogs[len].replace('* Network', '- Network');
console.log(networkLogs.join('\n'));
networkLogs.length = 0;
}
});
return '';
}
if (msg.includes(SIGNAL_H5_LOCAL)) {
return msg.replace('➜ ', '-');
}
return msg.replace('➜ ', '*');
},
};
const REMOVED_MSGS = [
'build started...',
(msg) => {
return /built in [0-9]+ms\./.test(msg);
},
'watching for file changes...',
];
exports.removeInfoFormatter = {
test(msg) {
return !!REMOVED_MSGS.find((m) => ((0, shared_1.isString)(m) ? msg.includes(m) : m(msg)));
},
format() {
return '';
},
};
const REMOVED_WARN_MSGS = [];
exports.removeWarnFormatter = {
test(msg) {
return !!REMOVED_WARN_MSGS.find((m) => msg.includes(m));
},
format() {
return '';
},
};
exports.errorFormatter = {
test(_, opts) {
return !!(opts && opts.error);
},
format(_, opts) {
return buildErrorMessage(opts.error, [], false);
},
};
function buildErrorMessage(err, args = [], includeStack = true) {
if (err.plugin) {
const otherMsgs = [];
if (err.message.includes(': [plugin ')) {
const messages = err.message.split(': [plugin ');
err.message = messages[0];
messages.slice(1).forEach((msg) => {
otherMsgs.push(`[plugin:${msg}`);
});
}
args.push(`${picocolors_1.default.magenta('[plugin:' + err.plugin + ']')} ${picocolors_1.default.red(err.message)}`);
args.push(...otherMsgs);
if (err.loc &&
err.hook === 'transform' &&
err.plugin === 'rollup-plugin-dynamic-import-variables' &&
err.id &&
constants_1.EXTNAME_VUE_RE.test(err.id)) {
try {
const ast = (0, ast_1.parseVue)(fs_1.default.readFileSync(err.id, 'utf8'), []);
const scriptNode = ast.children.find((node) => node.type === compiler_core_1.NodeTypes.ELEMENT && node.tag === 'script');
if (scriptNode) {
const scriptLoc = scriptNode.loc;
args.push(picocolors_1.default.yellow(pad((0, utils_2.generateCodeFrame)(scriptLoc.source, err.loc))));
// correct error location
err.loc.line = scriptLoc.start.line + err.loc.line - 1;
}
}
catch (e) { }
}
}
else {
args.push(picocolors_1.default.red(err.message));
}
if (err.id) {
args.push(formatAtFilename(err.id, err.loc?.line, err.loc?.column));
}
if (err.frame) {
args.push(picocolors_1.default.yellow(pad(err.frame)));
}
if (includeStack && err.stack) {
args.push(pad(cleanStack(err.stack)));
}
return args.join('\n');
}
function cleanStack(stack) {
return stack
.split(/\n/g)
.filter((l) => /^\s*at/.test(l))
.join('\n');
}
const splitRE = /\r?\n/;
function pad(source, n = 2) {
const lines = source.split(splitRE);
return lines.map((l) => ` `.repeat(n) + l).join(`\n`);
}
+10
View File
@@ -0,0 +1,10 @@
export declare function initI18nOptions(platform: UniApp.PLATFORM, inputDir: string, warning?: boolean, withMessages?: boolean): {
locale: string;
locales: Record<string, Record<string, string>>;
delimiters: [string, string];
} | undefined;
export declare const initI18nOptionsOnce: typeof initI18nOptions;
export declare function isUniAppLocaleFile(filepath: string): boolean;
export declare function getLocaleFiles(cwd: string): string[];
export declare function initLocales(dir: string, withMessages?: boolean): Record<string, Record<string, string>>;
export declare function resolveI18nLocale(platform: UniApp.PLATFORM, locales: string[], locale?: string): string;
+94
View File
@@ -0,0 +1,94 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveI18nLocale = exports.initLocales = exports.getLocaleFiles = exports.isUniAppLocaleFile = exports.initI18nOptionsOnce = exports.initI18nOptions = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const fast_glob_1 = require("fast-glob");
const shared_1 = require("@vue/shared");
const uni_shared_1 = require("@dcloudio/uni-shared");
const json_1 = require("./json");
const messages_1 = require("./messages");
function initI18nOptions(platform, inputDir, warning = false, withMessages = true) {
const locales = initLocales(path_1.default.resolve(inputDir, 'locale'), withMessages);
if (!Object.keys(locales).length) {
return;
}
const manifestJson = (0, json_1.parseManifestJsonOnce)(inputDir);
let fallbackLocale = manifestJson.fallbackLocale || 'en';
const locale = resolveI18nLocale(platform, Object.keys(locales), fallbackLocale);
if (warning) {
if (!fallbackLocale) {
console.warn(messages_1.M['i18n.fallbackLocale.default'].replace('{locale}', locale));
}
else if (locale !== fallbackLocale) {
console.warn(messages_1.M['i18n.fallbackLocale.missing'].replace('{locale}', fallbackLocale));
}
}
return {
locale,
locales,
delimiters: uni_shared_1.I18N_JSON_DELIMITERS,
};
}
exports.initI18nOptions = initI18nOptions;
exports.initI18nOptionsOnce = (0, uni_shared_1.once)(initI18nOptions);
const localeJsonRE = /uni-app.*.json/;
function isUniAppLocaleFile(filepath) {
if (!filepath) {
return false;
}
return localeJsonRE.test(path_1.default.basename(filepath));
}
exports.isUniAppLocaleFile = isUniAppLocaleFile;
function parseLocaleJson(filepath) {
let jsonObj = (0, json_1.parseJson)(fs_1.default.readFileSync(filepath, 'utf8'));
if (isUniAppLocaleFile(filepath)) {
jsonObj = jsonObj.common || {};
}
return jsonObj;
}
function getLocaleFiles(cwd) {
return (0, fast_glob_1.sync)('*.json', { cwd, absolute: true });
}
exports.getLocaleFiles = getLocaleFiles;
function initLocales(dir, withMessages = true) {
if (!fs_1.default.existsSync(dir)) {
return {};
}
return fs_1.default.readdirSync(dir).reduce((res, filename) => {
if (path_1.default.extname(filename) === '.json') {
try {
const locale = path_1.default
.basename(filename)
.replace(/(uni-app.)?(.*).json/, '$2');
if (withMessages) {
(0, shared_1.extend)(res[locale] || (res[locale] = {}), parseLocaleJson(path_1.default.join(dir, filename)));
}
else {
res[locale] = {};
}
}
catch (e) { }
}
return res;
}, {});
}
exports.initLocales = initLocales;
function resolveI18nLocale(platform, locales, locale) {
if (locale && locales.includes(locale)) {
return locale;
}
const defaultLocales = ['zh-Hans', 'zh-Hant'];
if (platform === 'app' || platform === 'h5') {
defaultLocales.unshift('en');
}
else {
// 小程序
defaultLocales.push('en');
}
return defaultLocales.find((locale) => locales.includes(locale)) || locales[0];
}
exports.resolveI18nLocale = resolveI18nLocale;
+28
View File
@@ -0,0 +1,28 @@
export * from './fs';
export * from './mp';
export * from './url';
export * from './env';
export * from './hbx';
export * from './ssr';
export * from './vue';
export * from './uts';
export * from './logs';
export * from './i18n';
export * from './deps';
export * from './json';
export * from './vite';
export * from './utils';
export * from './easycom';
export * from './constants';
export * from './preprocess';
export * from './postcss';
export * from './filter';
export * from './esbuild';
export * from './resolve';
export * from './scripts';
export * from './platform';
export * from './utsUtils';
export { parseUniExtApi, parseUniExtApis, parseInjects, parseUniModulesArtifacts, Define, DefineOptions, Defines, getUniExtApiProviderRegisters, resolveEncryptUniModule, formatExtApiProviderName, } from './uni_modules';
export { M } from './messages';
export * from './exports';
export { checkUpdate } from './checkUpdate';
+54
View File
@@ -0,0 +1,54 @@
"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 });
exports.checkUpdate = exports.M = exports.formatExtApiProviderName = exports.resolveEncryptUniModule = exports.getUniExtApiProviderRegisters = exports.parseUniModulesArtifacts = exports.parseInjects = exports.parseUniExtApis = exports.parseUniExtApi = void 0;
__exportStar(require("./fs"), exports);
__exportStar(require("./mp"), exports);
__exportStar(require("./url"), exports);
__exportStar(require("./env"), exports);
__exportStar(require("./hbx"), exports);
__exportStar(require("./ssr"), exports);
__exportStar(require("./vue"), exports);
__exportStar(require("./uts"), exports);
__exportStar(require("./logs"), exports);
__exportStar(require("./i18n"), exports);
__exportStar(require("./deps"), exports);
__exportStar(require("./json"), exports);
__exportStar(require("./vite"), exports);
__exportStar(require("./utils"), exports);
__exportStar(require("./easycom"), exports);
__exportStar(require("./constants"), exports);
__exportStar(require("./preprocess"), exports);
__exportStar(require("./postcss"), exports);
__exportStar(require("./filter"), exports);
__exportStar(require("./esbuild"), exports);
__exportStar(require("./resolve"), exports);
__exportStar(require("./scripts"), exports);
__exportStar(require("./platform"), exports);
__exportStar(require("./utsUtils"), exports);
var uni_modules_1 = require("./uni_modules");
Object.defineProperty(exports, "parseUniExtApi", { enumerable: true, get: function () { return uni_modules_1.parseUniExtApi; } });
Object.defineProperty(exports, "parseUniExtApis", { enumerable: true, get: function () { return uni_modules_1.parseUniExtApis; } });
Object.defineProperty(exports, "parseInjects", { enumerable: true, get: function () { return uni_modules_1.parseInjects; } });
Object.defineProperty(exports, "parseUniModulesArtifacts", { enumerable: true, get: function () { return uni_modules_1.parseUniModulesArtifacts; } });
Object.defineProperty(exports, "getUniExtApiProviderRegisters", { enumerable: true, get: function () { return uni_modules_1.getUniExtApiProviderRegisters; } });
Object.defineProperty(exports, "resolveEncryptUniModule", { enumerable: true, get: function () { return uni_modules_1.resolveEncryptUniModule; } });
Object.defineProperty(exports, "formatExtApiProviderName", { enumerable: true, get: function () { return uni_modules_1.formatExtApiProviderName; } });
var messages_1 = require("./messages");
Object.defineProperty(exports, "M", { enumerable: true, get: function () { return messages_1.M; } });
__exportStar(require("./exports"), exports);
var checkUpdate_1 = require("./checkUpdate");
Object.defineProperty(exports, "checkUpdate", { enumerable: true, get: function () { return checkUpdate_1.checkUpdate; } });
+3
View File
@@ -0,0 +1,3 @@
export * from './pages';
export * from './manifest';
export { polyfillCode, arrayBufferCode, restoreGlobalCode } from './pages/code';
+23
View File
@@ -0,0 +1,23 @@
"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 });
exports.restoreGlobalCode = exports.arrayBufferCode = exports.polyfillCode = void 0;
__exportStar(require("./pages"), exports);
__exportStar(require("./manifest"), exports);
var code_1 = require("./pages/code");
Object.defineProperty(exports, "polyfillCode", { enumerable: true, get: function () { return code_1.polyfillCode; } });
Object.defineProperty(exports, "arrayBufferCode", { enumerable: true, get: function () { return code_1.arrayBufferCode; } });
Object.defineProperty(exports, "restoreGlobalCode", { enumerable: true, get: function () { return code_1.restoreGlobalCode; } });
@@ -0,0 +1,2 @@
export declare function initArguments(manifestJson: Record<string, any>, pagesJson: UniApp.PagesJson): void;
export declare function parseArguments(pagesJson: UniApp.PagesJson): string | undefined;
@@ -0,0 +1,35 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseArguments = exports.initArguments = void 0;
function initArguments(manifestJson, pagesJson) {
const args = parseArguments(pagesJson);
if (args) {
manifestJson.plus.arguments = args;
}
}
exports.initArguments = initArguments;
function parseArguments(pagesJson) {
if (process.env.NODE_ENV !== 'development') {
return;
}
// 指定了入口
if (process.env.UNI_CLI_LAUNCH_PAGE_PATH) {
return JSON.stringify({
path: process.env.UNI_CLI_LAUNCH_PAGE_PATH,
query: process.env.UNI_CLI_LAUNCH_PAGE_QUERY,
});
}
const condition = pagesJson.condition;
if (condition && condition.list?.length) {
const list = condition.list;
let current = condition.current || 0;
if (current < 0) {
current = 0;
}
if (current >= list.length) {
current = 0;
}
return JSON.stringify(list[current]);
}
}
exports.parseArguments = parseArguments;
@@ -0,0 +1 @@
export declare function initCheckSystemWebview(manifestJson: Record<string, any>): void;
@@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initCheckSystemWebview = void 0;
function initCheckSystemWebview(manifestJson) {
// 检查Android系统webview版本 || 下载X5后启动
let plusWebView = manifestJson.plus.webView;
if (plusWebView) {
manifestJson.plus['uni-app'].webView = plusWebView;
delete manifestJson.plus.webView;
}
else {
manifestJson.plus['uni-app'].webView = {
minUserAgentVersion: '49.0',
};
}
}
exports.initCheckSystemWebview = initCheckSystemWebview;

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