2025/2/8第一次更新

This commit is contained in:
爱吃咸鱼小猫咪
2025-02-08 18:50:38 +08:00
commit d7af560866
26519 changed files with 5046029 additions and 0 deletions
+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.
+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: (isX: boolean) => {
showModal: string[];
showToast: string[];
showActionSheet: string[];
previewImage: string[];
openLocation: string[];
chooseLocation: string[];
};
export declare const COMPONENT_DEPS_CSS: (isX: boolean) => {
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[];
};
+53
View File
@@ -0,0 +1,53 @@
"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';
const API_DEPS_CSS = (isX) => {
return {
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: [
...(isX
? [
`${constants_1.BASE_COMPONENTS_STYLE_PATH}/view.css`,
`${constants_1.BASE_COMPONENTS_STYLE_PATH}/text.css`,
]
: [`${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.API_DEPS_CSS = API_DEPS_CSS;
const COMPONENT_DEPS_CSS = (isX) => {
return {
canvas: [RESIZE_SENSOR_CSS],
image: [RESIZE_SENSOR_CSS],
'movable-area': [RESIZE_SENSOR_CSS],
'picker-view': [RESIZE_SENSOR_CSS],
'picker-view-column': [RESIZE_SENSOR_CSS],
'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],
};
};
exports.COMPONENT_DEPS_CSS = COMPONENT_DEPS_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);
}
};
// ext-api 模式下,不存在 easycom 特性
if (process.env.UNI_COMPILE_TARGET !== 'ext-api') {
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();
if (process.env.UNI_COMPILE_TARGET !== 'ext-api') {
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));
}
// 加密插件easycom类型导入
if (source.includes('?uts-proxy')) {
const moduleId = path_1.default.basename(source.split('?uts-proxy')[0]);
source = `uts.sdk.modules.${(0, shared_1.camelize)(moduleId)}`;
}
const ident = genUTSComponentPublicInstanceIdent(tagName);
addUTSEasyComAutoImports(source, [ident, ident]);
});
}
(0, shared_1.extend)(easycomsObj, autoEasyComObj);
}
if (custom) {
Object.keys(custom).forEach((name) => {
const componentPath = custom[name];
easycomsObj[name] = componentPath.startsWith('@/')
? (0, utils_1.normalizePath)(path_1.default.join(rootDir, componentPath.slice(2)))
: componentPath;
});
}
Object.keys(easycomsObj).forEach((name) => {
easycoms.push({
name: name.startsWith('^') && name.endsWith('$') ? name.slice(1, -1) : name,
pattern: new RegExp(name),
replacement: easycomsObj[name],
});
});
debugEasycom(easycoms);
hasEasycom = !!easycoms.length;
return easycoms;
}
function matchEasycom(tag) {
if (!hasEasycom) {
return;
}
let source = easycomsCache.get(tag);
if (source) {
return source;
}
if (easycomsInvalidCache.has(tag)) {
return false;
}
const matcher = easycoms.find((matcher) => matcher.pattern.test(tag));
if (!matcher) {
easycomsInvalidCache.add(tag);
return false;
}
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_easycom_encrypt_uni_modules = // uni_modules模式不需要此逻辑
process.env.UNI_COMPILE_TARGET !== 'uni_modules' &&
is_uni_modules &&
// 前端加密插件,不能包含utssdk目录
fs_1.default.existsSync(path_1.default.resolve(dir, '../encrypt')) &&
!fs_1.default.existsSync(path_1.default.resolve(dir, '../utssdk'));
const uni_modules_plugin_id = is_easycom_encrypt_uni_modules && path_1.default.basename(path_1.default.resolve(dir, '..'));
fs_1.default.readdirSync(dir).forEach((name) => {
const folder = path_1.default.resolve(dir, name);
if (!isDir(folder)) {
return;
}
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_easycom_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;
};
+52
View File
@@ -0,0 +1,52 @@
"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;
process.env['UNI_APP_ID'] = manifestJson.appid;
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;
+8
View File
@@ -0,0 +1,8 @@
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 removeDuplicatePluginFormatter: Formatter;
export declare const errorFormatter: Formatter<LogErrorOptions>;
+196
View File
@@ -0,0 +1,196 @@
"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.removeDuplicatePluginFormatter = 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) {
filename = filename.replace('\x00', '').split('?')[0];
const file = process.env.UNI_INPUT_DIR
? path_1.default.relative(process.env.UNI_INPUT_DIR, filename)
: filename;
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.removeDuplicatePluginFormatter = {
test() {
return true;
},
format(msg) {
// [plugin:vite:vue] [plugin vite:vue]
// 正则匹配获取第一个插件名称,然后移除 [plugin vite:vue]
const pluginName = msg.match(/\[plugin\s([^\]]+)\]/)?.[1];
if (pluginName) {
return msg.replace(`[plugin ${pluginName}]`, '');
}
return msg;
},
};
exports.errorFormatter = {
test(_, opts) {
return !!(opts && opts.error);
},
format(_, opts) {
return buildErrorMessage(opts.error, [], false);
},
};
function buildErrorMessage(err, args = [], includeStack = true) {
if (err.plugin) {
// 避免出现这样的错误:[plugin:vite:vue] [plugin vite:vue]
if (err.message.startsWith(`[plugin ${err.plugin}]`)) {
let msg = err.message.replace(`[plugin ${err.plugin}]`, '');
if (err.loc) {
// [plugin:vite:vue] pages/index/index.vue (2:12): v-on="" is not supported
const locStr = `(${err.loc.line}:${err.loc.column}):`;
if (msg.includes(locStr)) {
msg = msg.split(locStr)[1];
}
}
args.push(`${picocolors_1.default.magenta('[plugin:' + err.plugin + ']')} ${picocolors_1.default.red(msg)}`);
}
else {
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;
+29
View File
@@ -0,0 +1,29 @@
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, Define, DefineOptions, Defines, getUniExtApiProviderRegisters, formatExtApiProviderName, } from './uni_modules';
export { parseUniModulesArtifacts, resolveEncryptUniModule, } from './uni_modules.cloud';
export { M } from './messages';
export * from './exports';
export { checkUpdate } from './checkUpdate';
+55
View File
@@ -0,0 +1,55 @@
"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.resolveEncryptUniModule = exports.parseUniModulesArtifacts = exports.formatExtApiProviderName = exports.getUniExtApiProviderRegisters = 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, "getUniExtApiProviderRegisters", { enumerable: true, get: function () { return uni_modules_1.getUniExtApiProviderRegisters; } });
Object.defineProperty(exports, "formatExtApiProviderName", { enumerable: true, get: function () { return uni_modules_1.formatExtApiProviderName; } });
var uni_modules_cloud_1 = require("./uni_modules.cloud");
Object.defineProperty(exports, "parseUniModulesArtifacts", { enumerable: true, get: function () { return uni_modules_cloud_1.parseUniModulesArtifacts; } });
Object.defineProperty(exports, "resolveEncryptUniModule", { enumerable: true, get: function () { return uni_modules_cloud_1.resolveEncryptUniModule; } });
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;
@@ -0,0 +1,4 @@
export declare const APP_CONFUSION_FILENAME = "app-confusion.js";
export declare function isConfusionFile(filename: string): boolean;
export declare function hasConfusionFile(inputDir?: string): boolean;
export declare function initConfusion(manifestJson: Record<string, any>): void;
@@ -0,0 +1,75 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.initConfusion = exports.hasConfusionFile = exports.isConfusionFile = exports.APP_CONFUSION_FILENAME = void 0;
const path_1 = __importDefault(require("path"));
const utils_1 = require("../../../utils");
const constants_1 = require("../../../constants");
const manifest_1 = require("../../manifest");
function isJsFile(filename) {
return constants_1.EXTNAME_JS_RE.test(filename);
}
function isStaticJsFile(filename) {
return (filename.indexOf('hybrid/html') === 0 ||
filename.indexOf('static/') === 0 ||
filename.indexOf('/static/') !== -1); // subpackages, uni_modules 中的 static 目录
}
const dynamicConfusionJsFiles = [];
exports.APP_CONFUSION_FILENAME = 'app-confusion.js';
function isConfusionFile(filename) {
return dynamicConfusionJsFiles.includes((0, utils_1.normalizePath)(filename));
}
exports.isConfusionFile = isConfusionFile;
function hasConfusionFile(inputDir) {
if (inputDir) {
const manifestJson = (0, manifest_1.parseManifestJsonOnce)(inputDir);
const resources = manifestJson['app-plus']?.confusion?.resources;
if (resources && parseConfusion(resources)[1].length) {
return true;
}
}
return !!dynamicConfusionJsFiles.length;
}
exports.hasConfusionFile = hasConfusionFile;
function parseConfusion(resources) {
const res = {};
const dynamicJsFiles = [];
Object.keys(resources).reduce((res, name) => {
const extname = path_1.default.extname(name);
if (extname === '.nvue') {
res[name.replace('.nvue', '.js')] = resources[name];
}
else if (isJsFile(name)) {
// 静态 js 加密
if (isStaticJsFile(name)) {
res[name] = resources[name];
}
else {
// 非静态 js 将被合并进 app-confusion.js
dynamicJsFiles.push(name);
}
}
else {
throw new Error(`原生混淆仅支持 nvue 页面,错误的页面路径:${name}`);
}
// TODO 旧编译器会检查要加密的 nvue 页面(包括subnvue)是否被使用?后续有时间再考虑支持吧,意义不太大
return res;
}, res);
if (dynamicJsFiles.length) {
res[exports.APP_CONFUSION_FILENAME] = {};
}
return [res, dynamicJsFiles];
}
function initConfusion(manifestJson) {
dynamicConfusionJsFiles.length = 0;
if (!manifestJson.plus.confusion?.resources) {
return;
}
const resources = manifestJson.plus.confusion.resources;
const [res, dynamicJsFiles] = parseConfusion(resources);
manifestJson.plus.confusion.resources = res;
dynamicConfusionJsFiles.push(...dynamicJsFiles);
}
exports.initConfusion = initConfusion;
@@ -0,0 +1 @@
export declare function initDefaultManifestJson(): any;
@@ -0,0 +1,47 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initDefaultManifestJson = void 0;
function initDefaultManifestJson() {
return JSON.parse(defaultManifestJson);
}
exports.initDefaultManifestJson = initDefaultManifestJson;
const defaultManifestJson = `{
"@platforms": [
"android",
"iPhone",
"iPad"
],
"id": "__WEAPP_ID",
"name": "__WEAPP_NAME",
"version": {
"name": "1.0",
"code": ""
},
"description": "",
"developer": {
"name": "",
"email": "",
"url": ""
},
"permissions": {},
"plus": {
"useragent": {
"value": "",
"concatenate": true
},
"splashscreen": {
"target":"id:1",
"autoclose": true,
"waiting": true,
"alwaysShowBeforeRender":true
},
"popGesture": "close",
"launchwebview": {}
},
"app-harmony": {
"useragent": {
"value": "",
"concatenate": true
}
}
}`;
@@ -0,0 +1,3 @@
export declare function getAppRenderer(manifestJson: Record<string, any>): "" | "native";
export declare function getAppCodeSpliting(manifestJson: Record<string, any>): boolean;
export declare function getAppStyleIsolation(manifestJson: Record<string, any>): 'apply-shared' | 'isolated' | 'shared';
+22
View File
@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getAppStyleIsolation = exports.getAppCodeSpliting = exports.getAppRenderer = void 0;
function getAppRenderer(manifestJson) {
const platformOptions = manifestJson['app-plus'];
if (platformOptions && platformOptions.renderer === 'native') {
return 'native';
}
return '';
}
exports.getAppRenderer = getAppRenderer;
function getAppCodeSpliting(manifestJson) {
if (manifestJson['app-plus']?.optimization?.codeSpliting === true) {
return true;
}
return false;
}
exports.getAppCodeSpliting = getAppCodeSpliting;
function getAppStyleIsolation(manifestJson) {
return (manifestJson['app-plus']?.optimization?.styleIsolation ?? 'apply-shared');
}
exports.getAppStyleIsolation = getAppStyleIsolation;
@@ -0,0 +1 @@
export declare function initI18n(manifestJson: Record<string, any>): Record<string, any>;
+14
View File
@@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initI18n = void 0;
const uni_i18n_1 = require("@dcloudio/uni-i18n");
const i18n_1 = require("../../../i18n");
function initI18n(manifestJson) {
const i18nOptions = (0, i18n_1.initI18nOptions)(process.env.UNI_PLATFORM, process.env.UNI_INPUT_DIR, true);
if (i18nOptions) {
manifestJson = JSON.parse((0, uni_i18n_1.compileI18nJsonStr)(JSON.stringify(manifestJson), i18nOptions));
manifestJson.fallbackLocale = i18nOptions.locale;
}
return manifestJson;
}
exports.initI18n = initI18n;
@@ -0,0 +1,5 @@
export declare function normalizeAppManifestJson(userManifestJson: Record<string, any>, pagesJson: UniApp.PagesJson): Record<string, any>;
export * from './env';
export { APP_CONFUSION_FILENAME, isConfusionFile, hasConfusionFile, } from './confusion';
export { getNVueCompiler, getNVueStyleCompiler, getNVueFlexDirection, } from './nvue';
export { parseArguments } from './arguments';
+63
View File
@@ -0,0 +1,63 @@
"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.parseArguments = exports.getNVueFlexDirection = exports.getNVueStyleCompiler = exports.getNVueCompiler = exports.hasConfusionFile = exports.isConfusionFile = exports.APP_CONFUSION_FILENAME = exports.normalizeAppManifestJson = void 0;
const shared_1 = require("@vue/shared");
const merge_1 = require("./merge");
const defaultManifestJson_1 = require("./defaultManifestJson");
const statusbar_1 = require("./statusbar");
const plus_1 = require("./plus");
const nvue_1 = require("./nvue");
const arguments_1 = require("./arguments");
const safearea_1 = require("./safearea");
const splashscreen_1 = require("./splashscreen");
const confusion_1 = require("./confusion");
const uniApp_1 = require("./uniApp");
const launchwebview_1 = require("./launchwebview");
const checksystemwebview_1 = require("./checksystemwebview");
const tabBar_1 = require("./tabBar");
const i18n_1 = require("./i18n");
const theme_1 = require("../../theme");
function normalizeAppManifestJson(userManifestJson, pagesJson) {
const manifestJson = (0, merge_1.initRecursiveMerge)((0, defaultManifestJson_1.initDefaultManifestJson)(), userManifestJson);
const { pages, globalStyle, tabBar } = (0, theme_1.initTheme)(manifestJson, pagesJson);
(0, shared_1.extend)(pagesJson, JSON.parse(JSON.stringify({ pages, globalStyle, tabBar })));
(0, statusbar_1.initAppStatusbar)(manifestJson, pagesJson);
(0, arguments_1.initArguments)(manifestJson, pagesJson);
(0, plus_1.initPlus)(manifestJson, pagesJson);
(0, nvue_1.initNVue)(manifestJson, pagesJson);
(0, safearea_1.initSafearea)(manifestJson, pagesJson);
(0, splashscreen_1.initSplashscreen)(manifestJson, userManifestJson);
(0, confusion_1.initConfusion)(manifestJson);
(0, uniApp_1.initUniApp)(manifestJson);
// 依赖 initArguments 先执行
(0, tabBar_1.initTabBar)((0, launchwebview_1.initLaunchwebview)(manifestJson, pagesJson), manifestJson, pagesJson);
// 依赖 initUniApp 先执行
(0, checksystemwebview_1.initCheckSystemWebview)(manifestJson);
return (0, i18n_1.initI18n)(manifestJson);
}
exports.normalizeAppManifestJson = normalizeAppManifestJson;
__exportStar(require("./env"), exports);
var confusion_2 = require("./confusion");
Object.defineProperty(exports, "APP_CONFUSION_FILENAME", { enumerable: true, get: function () { return confusion_2.APP_CONFUSION_FILENAME; } });
Object.defineProperty(exports, "isConfusionFile", { enumerable: true, get: function () { return confusion_2.isConfusionFile; } });
Object.defineProperty(exports, "hasConfusionFile", { enumerable: true, get: function () { return confusion_2.hasConfusionFile; } });
var nvue_2 = require("./nvue");
Object.defineProperty(exports, "getNVueCompiler", { enumerable: true, get: function () { return nvue_2.getNVueCompiler; } });
Object.defineProperty(exports, "getNVueStyleCompiler", { enumerable: true, get: function () { return nvue_2.getNVueStyleCompiler; } });
Object.defineProperty(exports, "getNVueFlexDirection", { enumerable: true, get: function () { return nvue_2.getNVueFlexDirection; } });
var arguments_2 = require("./arguments");
Object.defineProperty(exports, "parseArguments", { enumerable: true, get: function () { return arguments_2.parseArguments; } });
@@ -0,0 +1 @@
export declare function initLaunchwebview(manifestJson: Record<string, any>, pagesJson: UniApp.PagesJson): string;
@@ -0,0 +1,53 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initLaunchwebview = void 0;
const shared_1 = require("@vue/shared");
function initLaunchwebview(manifestJson, pagesJson) {
let entryPagePath = pagesJson.pages[0].path;
// 依赖前置执行initArguments
if (manifestJson.plus.arguments) {
try {
const args = JSON.parse(manifestJson.plus.arguments);
if (args.path) {
entryPagePath = args.path;
}
}
catch (e) { }
}
if (manifestJson.plus.useragent.concatenate) {
if (manifestJson.plus.useragent.value) {
manifestJson.plus.useragent.value = [
'uni-app',
manifestJson.plus.useragent.value,
].join(' ');
}
else {
manifestJson.plus.useragent.value = 'uni-app';
}
}
if (manifestJson['app-harmony'].useragent.concatenate) {
if (manifestJson['app-harmony'].useragent.value) {
manifestJson['app-harmony'].useragent.value = [
'uni-app',
manifestJson['app-harmony'].useragent.value,
].join(' ');
}
else {
manifestJson['app-harmony'].useragent.value = 'uni-app';
}
}
(0, shared_1.extend)(manifestJson.plus.launchwebview, {
id: '1',
kernel: 'WKWebview',
});
// 首页为nvue
const entryPage = pagesJson.pages.find((p) => p.path === entryPagePath);
if (entryPage?.style.isNVue) {
manifestJson.plus.launchwebview.uniNView = { path: entryPagePath + '.js' };
}
else {
manifestJson.launch_path = '__uniappview.html';
}
return entryPagePath;
}
exports.initLaunchwebview = initLaunchwebview;
@@ -0,0 +1 @@
export declare function initRecursiveMerge(manifestJson: Record<string, any>, userManifestJson: Record<string, any>): Record<string, any>;
+22
View File
@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initRecursiveMerge = void 0;
const merge_1 = require("merge");
function initRecursiveMerge(manifestJson, userManifestJson) {
const platformConfig = {
plus: userManifestJson['app-plus'],
};
platformConfig['app-harmony'] = userManifestJson['app-harmony'];
return (0, merge_1.recursive)(true, manifestJson, {
id: userManifestJson.appid || '',
name: userManifestJson.name || '',
description: userManifestJson.description || '',
version: {
name: userManifestJson.versionName,
code: userManifestJson.versionCode,
},
locale: userManifestJson.locale,
uniStatistics: userManifestJson.uniStatistics,
}, platformConfig);
}
exports.initRecursiveMerge = initRecursiveMerge;
@@ -0,0 +1,4 @@
export declare function initNVue(manifestJson: Record<string, any>, pagesJson: UniApp.PagesJson): void;
export declare function getNVueCompiler(manifestJson: Record<string, any>): "uni-app" | "vue" | "weex" | "vite";
export declare function getNVueStyleCompiler(manifestJson: Record<string, any>): "uni-app" | "weex";
export declare function getNVueFlexDirection(manifestJson: Record<string, any>): "column" | "row" | "row-reverse" | "column-reverse";
+41
View File
@@ -0,0 +1,41 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getNVueFlexDirection = exports.getNVueStyleCompiler = exports.getNVueCompiler = exports.initNVue = void 0;
function initNVue(manifestJson, pagesJson) { }
exports.initNVue = initNVue;
function getNVueCompiler(manifestJson) {
const platformOptions = manifestJson['app-plus'];
if (platformOptions) {
const { nvueCompiler } = platformOptions;
if (nvueCompiler === 'weex') {
return 'weex';
}
if (nvueCompiler === 'vue') {
return 'vue';
}
if (nvueCompiler === 'vite') {
return 'vite';
}
}
return 'uni-app';
}
exports.getNVueCompiler = getNVueCompiler;
function getNVueStyleCompiler(manifestJson) {
const platformOptions = manifestJson['app-plus'];
if (platformOptions && platformOptions.nvueStyleCompiler === 'uni-app') {
return 'uni-app';
}
return 'weex';
}
exports.getNVueStyleCompiler = getNVueStyleCompiler;
const flexDirs = ['row', 'row-reverse', 'column', 'column-reverse'];
function getNVueFlexDirection(manifestJson) {
let flexDir = 'column';
const appPlusJson = manifestJson['app-plus'] || manifestJson['plus'];
if (appPlusJson?.nvue?.['flex-direction'] &&
flexDirs.includes(appPlusJson?.nvue?.['flex-direction'])) {
flexDir = appPlusJson.nvue['flex-direction'];
}
return flexDir;
}
exports.getNVueFlexDirection = getNVueFlexDirection;
@@ -0,0 +1 @@
export declare function initPlus(manifestJson: Record<string, any>, pagesJson: UniApp.PagesJson): void;
+131
View File
@@ -0,0 +1,131 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initPlus = void 0;
const shared_1 = require("@vue/shared");
const merge_1 = require("merge");
const wxPageOrientationMapping = {
auto: [
'portrait-primary',
'portrait-secondary',
'landscape-primary',
'landscape-secondary',
],
portrait: ['portrait-primary', 'portrait-secondary'],
landscape: ['landscape-primary', 'landscape-secondary'],
};
function initPlus(manifestJson, pagesJson) {
initUniStatistics(manifestJson);
// 转换为老版本配置
if (manifestJson.plus.modules) {
manifestJson.permissions = manifestJson.plus.modules;
delete manifestJson.plus.modules;
}
const distribute = manifestJson.plus.distribute;
if (distribute) {
if (distribute.android) {
manifestJson.plus.distribute.google = distribute.android;
delete manifestJson.plus.distribute.android;
}
if (distribute.ios) {
manifestJson.plus.distribute.apple = distribute.ios;
delete manifestJson.plus.distribute.ios;
}
if (distribute.sdkConfigs) {
manifestJson.plus.distribute.plugins = distribute.sdkConfigs;
delete manifestJson.plus.distribute.sdkConfigs;
}
if (manifestJson.plus.darkmode) {
if (!(distribute.google || (distribute.google = {})).defaultNightMode) {
distribute.google.defaultNightMode = 'auto';
}
if (!(distribute.apple || (distribute.apple = {})).UIUserInterfaceStyle) {
distribute.apple.UIUserInterfaceStyle = 'Automatic';
}
}
}
// 屏幕启动方向
if (manifestJson.plus.screenOrientation) {
// app平台优先使用 manifest 配置
manifestJson.screenOrientation = manifestJson.plus.screenOrientation;
delete manifestJson.plus.screenOrientation;
}
else if (pagesJson.globalStyle?.pageOrientation) {
// 兼容微信小程序
const pageOrientationValue = wxPageOrientationMapping[pagesJson.globalStyle
.pageOrientation];
if (pageOrientationValue) {
manifestJson.screenOrientation = pageOrientationValue;
}
}
// 全屏配置
manifestJson.fullscreen = manifestJson.plus.fullscreen;
// 地图坐标系
if (manifestJson.permissions && manifestJson.permissions.Maps) {
manifestJson.permissions.Maps.coordType = 'gcj02';
}
if (!manifestJson.permissions) {
manifestJson.permissions = {};
}
manifestJson.permissions.UniNView = {
description: 'UniNView原生渲染',
};
// 允许内联播放视频
manifestJson.plus.allowsInlineMediaPlayback = true;
if (!manifestJson.plus.distribute) {
manifestJson.plus.distribute = {
plugins: {},
};
}
if (!manifestJson.plus.distribute.plugins) {
manifestJson.plus.distribute.plugins = {};
}
// 录音支持 mp3
manifestJson.plus.distribute.plugins.audio = {
mp3: {
description: 'Android平台录音支持MP3格式文件',
},
};
// 有效值为 close,none
if (!['close', 'none'].includes(manifestJson.plus.popGesture)) {
manifestJson.plus.popGesture = 'close';
}
}
exports.initPlus = initPlus;
function initUniStatistics(manifestJson) {
// 根节点配置了统计
if (manifestJson.uniStatistics) {
manifestJson.plus.uniStatistics = (0, merge_1.recursive)(true, manifestJson.uniStatistics, manifestJson.plus.uniStatistics);
manifestJson['app-harmony'].uniStatistics = (0, merge_1.recursive)(true, manifestJson.uniStatistics, manifestJson['app-harmony'].uniStatistics);
delete manifestJson.uniStatistics;
}
if (!process.env.UNI_CLOUD_PROVIDER) {
return;
}
let spaces = [];
try {
spaces = JSON.parse(process.env.UNI_CLOUD_PROVIDER);
}
catch (e) { }
if (!(0, shared_1.isArray)(spaces) || !spaces.length) {
return;
}
const space = spaces[0];
if (!space) {
return;
}
const uniStatistics = manifestJson.plus?.uniStatistics;
if (!uniStatistics) {
return;
}
if (uniStatistics.version === 2 || uniStatistics.version === '2') {
if (uniStatistics.uniCloud && uniStatistics.uniCloud.spaceId) {
return;
}
uniStatistics.uniCloud = {
provider: space.provider,
spaceId: space.spaceId,
clientSecret: space.clientSecret,
endpoint: space.endpoint,
};
}
}
@@ -0,0 +1 @@
export declare function initSafearea(manifestJson: Record<string, any>, pagesJson: UniApp.PagesJson): void;
@@ -0,0 +1,35 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initSafearea = void 0;
function initSafearea(manifestJson, pagesJson) {
if (pagesJson.tabBar?.list?.length) {
// 安全区配置 仅包含 tabBar 的时候才配置
if (!manifestJson.plus.safearea) {
manifestJson.plus.safearea = {
background: pagesJson.tabBar.backgroundColor || '#FFFFFF',
bottom: {
offset: 'auto',
},
};
}
if (!manifestJson['app-harmony'].safearea) {
manifestJson['app-harmony'].safearea = {
background: pagesJson.tabBar.backgroundColor || '#FFFFFF',
bottom: {
offset: 'auto',
},
};
}
}
else {
if (!manifestJson.plus.launchwebview) {
manifestJson.plus.launchwebview = {
render: 'always',
};
}
else if (!manifestJson.plus.launchwebview.render) {
manifestJson.plus.launchwebview.render = 'always';
}
}
}
exports.initSafearea = initSafearea;
@@ -0,0 +1,5 @@
export declare function initSplashscreen(manifestJson: Record<string, any>, userManifestJson: Record<string, any>): void;
export declare function getSplashscreen(manifestJson: Record<string, any>): {
autoclose: boolean;
alwaysShowBeforeRender: boolean;
};
@@ -0,0 +1,43 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSplashscreen = exports.initSplashscreen = void 0;
const shared_1 = require("@vue/shared");
function initSplashscreen(manifestJson, userManifestJson) {
if (!manifestJson.plus.splashscreen) {
return;
}
// 强制白屏检测
const splashscreenOptions = userManifestJson['app-plus'] && userManifestJson['app-plus'].splashscreen;
const hasAlwaysShowBeforeRender = splashscreenOptions && (0, shared_1.hasOwn)(splashscreenOptions, 'alwaysShowBeforeRender');
if (!hasAlwaysShowBeforeRender &&
manifestJson.plus.splashscreen.autoclose === false) {
// 兼容旧版本仅配置了 autoclose 为 false
manifestJson.plus.splashscreen.alwaysShowBeforeRender = false;
}
if (manifestJson.plus.splashscreen.alwaysShowBeforeRender) {
// 白屏检测
if (!manifestJson.plus.splashscreen.target) {
manifestJson.plus.splashscreen.target = 'id:1';
}
manifestJson.plus.splashscreen.autoclose = true;
manifestJson.plus.splashscreen.delay = 0;
}
else {
// 不启用白屏检测
delete manifestJson.plus.splashscreen.target;
if (manifestJson.plus.splashscreen.autoclose) {
// 启用 uni-app 框架关闭 splash
manifestJson.plus.splashscreen.autoclose = false; // 原 5+ autoclose 改为 false
}
}
delete manifestJson.plus.splashscreen.alwaysShowBeforeRender;
}
exports.initSplashscreen = initSplashscreen;
function getSplashscreen(manifestJson) {
const splashscreenOptions = manifestJson['app-plus']?.splashscreen || {};
return {
autoclose: splashscreenOptions.autoclose !== false,
alwaysShowBeforeRender: splashscreenOptions.alwaysShowBeforeRender !== false,
};
}
exports.getSplashscreen = getSplashscreen;
@@ -0,0 +1 @@
export declare function initAppStatusbar(manifestJson: Record<string, any>, pagesJson: UniApp.PagesJson): Record<string, any>;
@@ -0,0 +1,16 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initAppStatusbar = void 0;
function initAppStatusbar(manifestJson, pagesJson) {
const titleColor = pagesJson.pages[0].style.navigationBar.titleColor ||
pagesJson.globalStyle.navigationBar.titleColor ||
'#000000';
const backgroundColor = pagesJson.globalStyle.navigationBar.backgroundColor || '#000000';
manifestJson.plus.statusbar = {
immersed: 'supportedDevice',
style: titleColor === '#ffffff' ? 'light' : 'dark',
background: backgroundColor,
};
return manifestJson;
}
exports.initAppStatusbar = initAppStatusbar;
@@ -0,0 +1 @@
export declare function initTabBar(entryPagePath: string, manifestJson: Record<string, any>, pagesJson: UniApp.PagesJson): void;
+24
View File
@@ -0,0 +1,24 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initTabBar = void 0;
const uni_shared_1 = require("@dcloudio/uni-shared");
function initTabBar(entryPagePath, manifestJson, pagesJson) {
if (!pagesJson.tabBar?.list?.length) {
return;
}
const tabBar = JSON.parse(JSON.stringify(pagesJson.tabBar));
tabBar.borderStyle = (0, uni_shared_1.normalizeTabBarStyles)(tabBar.borderStyle);
if (!tabBar.selectedColor) {
tabBar.selectedColor = uni_shared_1.SELECTED_COLOR;
}
tabBar.height = `${parseFloat(tabBar.height) || uni_shared_1.TABBAR_HEIGHT}px`;
// 首页是 tabBar 页面
const item = tabBar.list.find((page) => page.pagePath === entryPagePath);
if (item) {
;
tabBar.child = ['lauchwebview'];
tabBar.selected = tabBar.list.indexOf(item);
}
manifestJson.plus.tabBar = tabBar;
}
exports.initTabBar = initTabBar;
@@ -0,0 +1 @@
export declare function initUniApp(manifestJson: Record<string, any>): void;
+19
View File
@@ -0,0 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initUniApp = void 0;
const nvue_1 = require("./nvue");
function initUniApp(manifestJson) {
manifestJson.plus['uni-app'] = {
control: 'uni-v3',
vueVersion: '3',
compilerVersion: process.env.UNI_COMPILER_VERSION,
nvueCompiler: (0, nvue_1.getNVueCompiler)(manifestJson),
renderer: 'auto',
nvue: {
'flex-direction': (0, nvue_1.getNVueFlexDirection)(manifestJson),
},
nvueLaunchMode: manifestJson.plus.nvueLaunchMode === 'fast' ? 'fast' : 'normal',
};
delete manifestJson.plus.nvueLaunchMode;
}
exports.initUniApp = initUniApp;
+4
View File
@@ -0,0 +1,4 @@
export declare const arrayBufferCode = "\nif (typeof uni !== 'undefined' && uni && uni.requireGlobal) {\n const global = uni.requireGlobal()\n ArrayBuffer = global.ArrayBuffer\n Int8Array = global.Int8Array\n Uint8Array = global.Uint8Array\n Uint8ClampedArray = global.Uint8ClampedArray\n Int16Array = global.Int16Array\n Uint16Array = global.Uint16Array\n Int32Array = global.Int32Array\n Uint32Array = global.Uint32Array\n Float32Array = global.Float32Array\n Float64Array = global.Float64Array\n BigInt64Array = global.BigInt64Array\n BigUint64Array = global.BigUint64Array\n};\n";
export declare const polyfillCode = "\nif (typeof Promise !== 'undefined' && !Promise.prototype.finally) {\n Promise.prototype.finally = function(callback) {\n const promise = this.constructor\n return this.then(\n value => promise.resolve(callback()).then(() => value),\n reason => promise.resolve(callback()).then(() => {\n throw reason\n })\n )\n }\n};\n\nif (typeof uni !== 'undefined' && uni && uni.requireGlobal) {\n const global = uni.requireGlobal()\n ArrayBuffer = global.ArrayBuffer\n Int8Array = global.Int8Array\n Uint8Array = global.Uint8Array\n Uint8ClampedArray = global.Uint8ClampedArray\n Int16Array = global.Int16Array\n Uint16Array = global.Uint16Array\n Int32Array = global.Int32Array\n Uint32Array = global.Uint32Array\n Float32Array = global.Float32Array\n Float64Array = global.Float64Array\n BigInt64Array = global.BigInt64Array\n BigUint64Array = global.BigUint64Array\n};\n\n";
export declare const restoreGlobalCode = "\nif(uni.restoreGlobal){\n uni.restoreGlobal(Vue,weex,plus,setTimeout,clearTimeout,setInterval,clearInterval)\n}\n";
export declare const globalCode: string;
+61
View File
@@ -0,0 +1,61 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.globalCode = exports.restoreGlobalCode = exports.polyfillCode = exports.arrayBufferCode = void 0;
exports.arrayBufferCode = `
if (typeof uni !== 'undefined' && uni && uni.requireGlobal) {
const global = uni.requireGlobal()
ArrayBuffer = global.ArrayBuffer
Int8Array = global.Int8Array
Uint8Array = global.Uint8Array
Uint8ClampedArray = global.Uint8ClampedArray
Int16Array = global.Int16Array
Uint16Array = global.Uint16Array
Int32Array = global.Int32Array
Uint32Array = global.Uint32Array
Float32Array = global.Float32Array
Float64Array = global.Float64Array
BigInt64Array = global.BigInt64Array
BigUint64Array = global.BigUint64Array
};
`;
exports.polyfillCode = `
if (typeof Promise !== 'undefined' && !Promise.prototype.finally) {
Promise.prototype.finally = function(callback) {
const promise = this.constructor
return this.then(
value => promise.resolve(callback()).then(() => value),
reason => promise.resolve(callback()).then(() => {
throw reason
})
)
}
};
${exports.arrayBufferCode}
`;
exports.restoreGlobalCode = `
if(uni.restoreGlobal){
uni.restoreGlobal(Vue,weex,plus,setTimeout,clearTimeout,setInterval,clearInterval)
}
`;
const GLOBALS = [
'global',
'window',
'document',
'frames',
'self',
'location',
'navigator',
'localStorage',
'history',
'Caches',
'screen',
'alert',
'confirm',
'prompt',
'fetch',
'XMLHttpRequest',
'WebSocket',
'webkit',
'print',
];
exports.globalCode = GLOBALS.map((g) => `${g}:u`).join(',');
@@ -0,0 +1,2 @@
export declare function definePageCode(pagesJson: Record<string, any>, platform?: UniApp.PLATFORM): string;
export declare function defineNVuePageCode(pagesJson: Record<string, any>): string;
@@ -0,0 +1,42 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.defineNVuePageCode = exports.definePageCode = void 0;
const utils_1 = require("../../../utils");
function definePageCode(pagesJson, platform = 'app') {
const importPagesCode = [];
const definePagesCode = [];
pagesJson.pages.forEach((page) => {
if (platform === 'app' && page.style.isNVue) {
return;
}
const pagePath = page.path;
const pageIdentifier = (0, utils_1.normalizeIdentifier)(pagePath);
const pagePathWithExtname = (0, utils_1.normalizePagePath)(pagePath, platform);
if (pagePathWithExtname) {
if (process.env.UNI_APP_CODE_SPLITING) {
// 拆分页面
importPagesCode.push(`const ${pageIdentifier} = ()=>import('./${pagePathWithExtname}')`);
}
else {
importPagesCode.push(`import ${pageIdentifier} from './${pagePathWithExtname}'`);
}
definePagesCode.push(`__definePage('${pagePath}',${pageIdentifier})`);
}
});
return importPagesCode.join('\n') + '\n' + definePagesCode.join('\n');
}
exports.definePageCode = definePageCode;
function defineNVuePageCode(pagesJson) {
const importNVuePagesCode = [];
pagesJson.pages.forEach((page) => {
if (!page.style.isNVue) {
return;
}
const pagePathWithExtname = (0, utils_1.normalizePagePath)(page.path, 'app');
if (pagePathWithExtname) {
importNVuePagesCode.push(`import('./${pagePathWithExtname}').then((res)=>{res.length})`);
}
});
return importNVuePagesCode.join('\n');
}
exports.defineNVuePageCode = defineNVuePageCode;
+3
View File
@@ -0,0 +1,3 @@
export declare function normalizeAppPagesJson(pagesJson: Record<string, any>, platform?: UniApp.PLATFORM): string;
export declare function normalizeAppNVuePagesJson(pagesJson: Record<string, any>): string;
export declare function normalizeAppConfigService(pagesJson: UniApp.PagesJson, manifestJson: Record<string, any>): string;
+29
View File
@@ -0,0 +1,29 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.normalizeAppConfigService = exports.normalizeAppNVuePagesJson = exports.normalizeAppPagesJson = void 0;
const code_1 = require("./code");
const definePage_1 = require("./definePage");
const uniConfig_1 = require("./uniConfig");
const uniRoutes_1 = require("./uniRoutes");
function normalizeAppPagesJson(pagesJson, platform = 'app') {
return (0, definePage_1.definePageCode)(pagesJson, platform);
}
exports.normalizeAppPagesJson = normalizeAppPagesJson;
function normalizeAppNVuePagesJson(pagesJson) {
return (0, definePage_1.defineNVuePageCode)(pagesJson);
}
exports.normalizeAppNVuePagesJson = normalizeAppNVuePagesJson;
function normalizeAppConfigService(pagesJson, manifestJson) {
return `
;(function(){
let u=void 0,isReady=false,onReadyCallbacks=[],isServiceReady=false,onServiceReadyCallbacks=[];
const __uniConfig = ${(0, uniConfig_1.normalizeAppUniConfig)(pagesJson, manifestJson)};
const __uniRoutes = ${(0, uniRoutes_1.normalizeAppUniRoutes)(pagesJson)}.map(uniRoute=>(uniRoute.meta.route=uniRoute.path,__uniConfig.pages.push(uniRoute.path),uniRoute.path='/'+uniRoute.path,uniRoute));
__uniConfig.styles=${process.env.UNI_NVUE_APP_STYLES || '[]'};//styles
__uniConfig.onReady=function(callback){if(__uniConfig.ready){callback()}else{onReadyCallbacks.push(callback)}};Object.defineProperty(__uniConfig,"ready",{get:function(){return isReady},set:function(val){isReady=val;if(!isReady){return}const callbacks=onReadyCallbacks.slice(0);onReadyCallbacks.length=0;callbacks.forEach(function(callback){callback()})}});
__uniConfig.onServiceReady=function(callback){if(__uniConfig.serviceReady){callback()}else{onServiceReadyCallbacks.push(callback)}};Object.defineProperty(__uniConfig,"serviceReady",{get:function(){return isServiceReady},set:function(val){isServiceReady=val;if(!isServiceReady){return}const callbacks=onServiceReadyCallbacks.slice(0);onServiceReadyCallbacks.length=0;callbacks.forEach(function(callback){callback()})}});
service.register("uni-app-config",{create(a,b,c){if(!__uniConfig.viewport){var d=b.weex.config.env.scale,e=b.weex.config.env.deviceWidth,f=Math.ceil(e/d);Object.assign(__uniConfig,{viewport:f,defaultFontSize:16})}return{instance:{__uniConfig:__uniConfig,__uniRoutes:__uniRoutes,${code_1.globalCode}}}}});
})();
`;
}
exports.normalizeAppConfigService = normalizeAppConfigService;
@@ -0,0 +1,6 @@
export declare function normalizeAppUniConfig(pagesJson: UniApp.PagesJson, manifestJson: Record<string, any>): string;
export declare function parseEntryPagePath(pagesJson: UniApp.PagesJson): {
entryPagePath: string;
entryPageQuery: string;
realEntryPagePath: string;
};
+75
View File
@@ -0,0 +1,75 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseEntryPagePath = exports.normalizeAppUniConfig = void 0;
const path_1 = __importDefault(require("path"));
const i18n_1 = require("../../../i18n");
const manifest_1 = require("../../manifest");
const manifest_2 = require("../manifest");
const arguments_1 = require("../manifest/arguments");
const splashscreen_1 = require("../manifest/splashscreen");
const theme_1 = require("../../theme");
function normalizeAppUniConfig(pagesJson, manifestJson) {
const { autoclose, alwaysShowBeforeRender } = (0, splashscreen_1.getSplashscreen)(manifestJson);
const platformConfig = (0, manifest_1.getPlatformManifestJsonOnce)();
const config = {
pages: [],
globalStyle: pagesJson.globalStyle,
nvue: {
compiler: (0, manifest_2.getNVueCompiler)(manifestJson),
styleCompiler: (0, manifest_2.getNVueStyleCompiler)(manifestJson),
'flex-direction': (0, manifest_2.getNVueFlexDirection)(manifestJson),
},
renderer: manifestJson['app-plus']?.renderer === 'native' ? 'native' : 'auto',
appname: manifestJson.name || '',
splashscreen: {
alwaysShowBeforeRender,
autoclose,
},
compilerVersion: process.env.UNI_COMPILER_VERSION,
...parseEntryPagePath(pagesJson),
networkTimeout: (0, manifest_1.normalizeNetworkTimeout)(manifestJson.networkTimeout),
tabBar: pagesJson.tabBar,
fallbackLocale: manifestJson.fallbackLocale,
locales: (0, i18n_1.initLocales)(path_1.default.join(process.env.UNI_INPUT_DIR, 'locale')),
darkmode: platformConfig.darkmode || false,
themeConfig: (0, theme_1.normalizeThemeConfigOnce)(platformConfig),
// @ts-expect-error
qqMapKey: platformConfig?.distribute?.sdkConfigs?.maps?.tencent?.key,
};
// TODO 待支持分包
return JSON.stringify(config);
}
exports.normalizeAppUniConfig = normalizeAppUniConfig;
function parseEntryPagePath(pagesJson) {
const res = {
entryPagePath: '',
entryPageQuery: '',
realEntryPagePath: '',
};
if (!pagesJson.pages.length) {
return res;
}
res.entryPagePath = pagesJson.pages[0].path;
const argsJsonStr = (0, arguments_1.parseArguments)(pagesJson);
if (argsJsonStr) {
try {
const args = JSON.parse(argsJsonStr);
const entryPagePath = args.path || args.pathName;
const realEntryPagePath = res.entryPagePath;
if (entryPagePath && realEntryPagePath !== entryPagePath) {
res.entryPagePath = entryPagePath;
res.entryPageQuery = args.query ? '?' + args.query : '';
// non tabBar page
if (!(pagesJson.tabBar?.list || []).find((page) => page.pagePath === entryPagePath)) {
res.realEntryPagePath = realEntryPagePath;
}
}
}
catch (e) { }
}
return res;
}
exports.parseEntryPagePath = parseEntryPagePath;
@@ -0,0 +1 @@
export declare function normalizeAppUniRoutes(pagesJson: UniApp.PagesJson): string;
@@ -0,0 +1,8 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.normalizeAppUniRoutes = void 0;
const pages_1 = require("../../pages");
function normalizeAppUniRoutes(pagesJson) {
return JSON.stringify((0, pages_1.normalizePagesRoute)(pagesJson));
}
exports.normalizeAppUniRoutes = normalizeAppUniRoutes;
+7
View File
@@ -0,0 +1,7 @@
export * from './mp';
export * from './app';
export * from './json';
export * from './pages';
export * from './manifest';
export * from './theme';
export { normalizeUniAppXAppPagesJson, normalizeUniAppXAppConfig, checkPagesJson, parseUniXFlexDirection, parseUniXSplashScreen, parseUniXUniStatistics, } from './uni-x';
+30
View File
@@ -0,0 +1,30 @@
"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.parseUniXUniStatistics = exports.parseUniXSplashScreen = exports.parseUniXFlexDirection = exports.checkPagesJson = exports.normalizeUniAppXAppConfig = exports.normalizeUniAppXAppPagesJson = void 0;
__exportStar(require("./mp"), exports);
__exportStar(require("./app"), exports);
__exportStar(require("./json"), exports);
__exportStar(require("./pages"), exports);
__exportStar(require("./manifest"), exports);
__exportStar(require("./theme"), exports);
var uni_x_1 = require("./uni-x");
Object.defineProperty(exports, "normalizeUniAppXAppPagesJson", { enumerable: true, get: function () { return uni_x_1.normalizeUniAppXAppPagesJson; } });
Object.defineProperty(exports, "normalizeUniAppXAppConfig", { enumerable: true, get: function () { return uni_x_1.normalizeUniAppXAppConfig; } });
Object.defineProperty(exports, "checkPagesJson", { enumerable: true, get: function () { return uni_x_1.checkPagesJson; } });
Object.defineProperty(exports, "parseUniXFlexDirection", { enumerable: true, get: function () { return uni_x_1.parseUniXFlexDirection; } });
Object.defineProperty(exports, "parseUniXSplashScreen", { enumerable: true, get: function () { return uni_x_1.parseUniXSplashScreen; } });
Object.defineProperty(exports, "parseUniXUniStatistics", { enumerable: true, get: function () { return uni_x_1.parseUniXUniStatistics; } });
+1
View File
@@ -0,0 +1 @@
export declare function parseJson(jsonStr: string, shouldPre?: boolean): any;
+13
View File
@@ -0,0 +1,13 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseJson = void 0;
const jsonc_parser_1 = require("jsonc-parser");
const preprocess_1 = require("../preprocess");
function parseJson(jsonStr, shouldPre = false) {
return (0, jsonc_parser_1.parse)(shouldPre
? process.env.UNI_APP_X === 'true'
? (0, preprocess_1.preUVueJson)(jsonStr)
: (0, preprocess_1.preJson)(jsonStr)
: jsonStr);
}
exports.parseJson = parseJson;
+36
View File
@@ -0,0 +1,36 @@
export declare const parseManifestJson: (inputDir: string) => any;
export declare const parseManifestJsonOnce: (inputDir: string) => any;
export declare const parseRpx2UnitOnce: (inputDir: string, platform?: UniApp.PLATFORM) => any;
interface CompilerCompatConfig {
MODE?: 2 | 3;
}
declare function parseCompatConfig(_inputDir: string): CompilerCompatConfig;
export declare const parseCompatConfigOnce: typeof parseCompatConfig;
declare const defaultNetworkTimeout: {
request: number;
connectSocket: number;
uploadFile: number;
downloadFile: number;
};
export declare function normalizeNetworkTimeout(networkTimeout?: Partial<typeof defaultNetworkTimeout>): {
request: number;
connectSocket: number;
uploadFile: number;
downloadFile: number;
};
export declare function getUniStatistics(inputDir: string, platform: UniApp.PLATFORM): any;
export declare function isEnableUniPushV1(inputDir: string, platform: UniApp.PLATFORM): boolean;
export declare function isEnableUniPushV2(inputDir: string, platform: UniApp.PLATFORM): boolean;
export declare function isEnableSecureNetwork(inputDir: string, platform: UniApp.PLATFORM): boolean;
export declare function hasPushModule(inputDir: string): boolean;
export declare function isUniPushOffline(inputDir: string): boolean;
export declare function getRouterOptions(manifestJson: Record<string, any>): {
mode?: 'history' | 'hash';
base?: string;
};
export declare function isEnableTreeShaking(manifestJson: Record<string, any>): boolean;
export declare function getDevServerOptions(manifestJson: Record<string, any>): any;
export declare function getPlatformManifestJson(manifestJson: any, platform?: UniApp.PLATFORM): any;
export declare function getPlatformManifestJsonOnce(): any;
export declare function validateThemeValue(value: string): boolean;
export {};
+144
View File
@@ -0,0 +1,144 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateThemeValue = exports.getPlatformManifestJsonOnce = exports.getPlatformManifestJson = exports.getDevServerOptions = exports.isEnableTreeShaking = exports.getRouterOptions = exports.isUniPushOffline = exports.hasPushModule = exports.isEnableSecureNetwork = exports.isEnableUniPushV2 = exports.isEnableUniPushV1 = exports.getUniStatistics = exports.normalizeNetworkTimeout = exports.parseCompatConfigOnce = exports.parseRpx2UnitOnce = exports.parseManifestJsonOnce = exports.parseManifestJson = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const shared_1 = require("@vue/shared");
const uni_shared_1 = require("@dcloudio/uni-shared");
const json_1 = require("./json");
const utils_1 = require("../utils");
const parseManifestJson = (inputDir) => {
const manifestFilename = path_1.default.join(inputDir, 'manifest.json');
if (!fs_1.default.existsSync(manifestFilename)) {
if (!(0, utils_1.isNormalCompileTarget)()) {
return {};
}
}
return (0, json_1.parseJson)(fs_1.default.readFileSync(path_1.default.join(inputDir, 'manifest.json'), 'utf8'));
};
exports.parseManifestJson = parseManifestJson;
exports.parseManifestJsonOnce = (0, uni_shared_1.once)(exports.parseManifestJson);
exports.parseRpx2UnitOnce = (0, uni_shared_1.once)((inputDir, platform = 'h5') => {
const rpx2unit = platform === 'h5' || platform === 'app' || platform === 'app-harmony'
? uni_shared_1.defaultRpx2Unit
: uni_shared_1.defaultMiniProgramRpx2Unit;
const manifestJson = (0, exports.parseManifestJsonOnce)(inputDir);
let platformOptions = getPlatformManifestJson(manifestJson, platform);
if (platformOptions && platformOptions.rpx) {
return (0, shared_1.extend)({}, rpx2unit, platformOptions);
}
return (0, shared_1.extend)({}, rpx2unit);
});
function parseCompatConfig(_inputDir) {
// 不支持 mode:2
return { MODE: 3 }; //parseManifestJsonOnce(inputDir).compatConfig || {}
}
exports.parseCompatConfigOnce = (0, uni_shared_1.once)(parseCompatConfig);
const defaultNetworkTimeout = {
request: 60000,
connectSocket: 60000,
uploadFile: 60000,
downloadFile: 60000,
};
function normalizeNetworkTimeout(networkTimeout) {
return {
...defaultNetworkTimeout,
...networkTimeout,
};
}
exports.normalizeNetworkTimeout = normalizeNetworkTimeout;
function getUniStatistics(inputDir, platform) {
const manifest = (0, exports.parseManifestJsonOnce)(inputDir);
let platformManifest = getPlatformManifestJson(manifest, platform);
return (0, shared_1.extend)({}, manifest.uniStatistics, platformManifest && platformManifest.uniStatistics);
}
exports.getUniStatistics = getUniStatistics;
function isEnableUniPushV1(inputDir, platform) {
if (isEnableUniPushV2(inputDir, platform)) {
return false;
}
const manifest = (0, exports.parseManifestJsonOnce)(inputDir);
if (platform === 'app') {
const push = manifest['app-plus']?.distribute?.sdkConfigs?.push;
if (push && (0, shared_1.hasOwn)(push, 'unipush')) {
return true;
}
}
return false;
}
exports.isEnableUniPushV1 = isEnableUniPushV1;
function isEnableUniPushV2(inputDir, platform) {
const manifest = (0, exports.parseManifestJsonOnce)(inputDir);
const platformManifest = getPlatformManifestJson(manifest, platform);
if (platform === 'app') {
return (platformManifest?.distribute?.sdkConfigs?.push?.unipush?.version == '2');
}
return platformManifest?.unipush?.enable === true;
}
exports.isEnableUniPushV2 = isEnableUniPushV2;
function isEnableSecureNetwork(inputDir, platform) {
const manifest = (0, exports.parseManifestJsonOnce)(inputDir);
const platformManifest = getPlatformManifestJson(manifest, platform);
if (platform === 'app') {
return !!platformManifest?.modules?.SecureNetwork;
}
return platformManifest?.secureNetwork?.enable === true;
}
exports.isEnableSecureNetwork = isEnableSecureNetwork;
function hasPushModule(inputDir) {
const manifest = (0, exports.parseManifestJsonOnce)(inputDir);
return !!manifest['app-plus']?.modules?.Push;
}
exports.hasPushModule = hasPushModule;
function isUniPushOffline(inputDir) {
const manifest = (0, exports.parseManifestJsonOnce)(inputDir);
return (manifest['app-plus']?.distribute?.sdkConfigs?.push?.unipush?.offline ===
true);
}
exports.isUniPushOffline = isUniPushOffline;
function getRouterOptions(manifestJson) {
return (0, shared_1.extend)({}, getPlatformManifestJson(manifestJson, 'h5')?.router);
}
exports.getRouterOptions = getRouterOptions;
function isEnableTreeShaking(manifestJson) {
// 自动化测试时,一定不摇树
if (process.env.UNI_AUTOMATOR_WS_ENDPOINT) {
return false;
}
const platformManifest = getPlatformManifestJson(manifestJson, 'h5');
return platformManifest?.optimization?.treeShaking?.enable !== false;
}
exports.isEnableTreeShaking = isEnableTreeShaking;
function getDevServerOptions(manifestJson) {
const platformManifest = getPlatformManifestJson(manifestJson, 'h5');
return (0, shared_1.extend)({}, platformManifest?.devServer);
}
exports.getDevServerOptions = getDevServerOptions;
function getPlatformManifestJson(manifestJson, platform) {
if (!platform) {
platform = process.env.UNI_PLATFORM;
}
if (platform === 'app') {
return manifestJson['app-plus'] || manifestJson['plus'] || {};
}
if (platform === 'h5') {
return manifestJson.web || manifestJson.h5 || {};
}
return manifestJson[platform] || {};
}
exports.getPlatformManifestJson = getPlatformManifestJson;
function getPlatformManifestJsonOnce() {
const manifestJson = !process.env.UNI_INPUT_DIR
? {}
: (0, exports.parseManifestJsonOnce)(process.env.UNI_INPUT_DIR);
return getPlatformManifestJson(manifestJson);
}
exports.getPlatformManifestJsonOnce = getPlatformManifestJsonOnce;
const themeValues = ['dark', 'light', 'auto'];
function validateThemeValue(value) {
return themeValues.indexOf(value) !== -1;
}
exports.validateThemeValue = validateThemeValue;
+4
View File
@@ -0,0 +1,4 @@
export * from './jsonFile';
export { AppJson, ComponentJson, MiniProgramComponentsType } from './types';
export { mergeMiniProgramAppJson, parseMiniProgramPagesJson } from './pages';
export { parseMiniProgramProjectJson } from './project';
+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.parseMiniProgramProjectJson = exports.parseMiniProgramPagesJson = exports.mergeMiniProgramAppJson = void 0;
__exportStar(require("./jsonFile"), exports);
var pages_1 = require("./pages");
Object.defineProperty(exports, "mergeMiniProgramAppJson", { enumerable: true, get: function () { return pages_1.mergeMiniProgramAppJson; } });
Object.defineProperty(exports, "parseMiniProgramPagesJson", { enumerable: true, get: function () { return pages_1.parseMiniProgramPagesJson; } });
var project_1 = require("./project");
Object.defineProperty(exports, "parseMiniProgramProjectJson", { enumerable: true, get: function () { return project_1.parseMiniProgramProjectJson; } });
+28
View File
@@ -0,0 +1,28 @@
import type { ComponentJson, MiniProgramComponentsType, PageWindowOptions, UsingComponents } from './types';
export declare function isMiniProgramPageFile(file: string, inputDir?: string): boolean;
export declare function isMiniProgramPageSfcFile(file: string, inputDir?: string): boolean;
export declare function hasJsonFile(filename: string): boolean;
export declare function getComponentJsonFilenames(): string[];
export declare function findJsonFile(filename: string): Record<string, any> | ComponentJson | PageWindowOptions | undefined;
export declare function findUsingComponents(filename: string): UsingComponents | undefined;
export declare function normalizeJsonFilename(filename: string): string;
export declare function findChangedJsonFiles(supportGlobalUsingComponents?: boolean): Map<string, string>;
export declare function addMiniProgramAppJson(appJson: Record<string, any>): void;
export declare function addMiniProgramPageJson(filename: string, json: PageWindowOptions): void;
export declare function addMiniProgramComponentJson(filename: string, json: ComponentJson): void;
export declare function addMiniProgramUsingComponents(filename: string, json: UsingComponents): void;
export declare function isMiniProgramUsingComponent(name: string, options: {
filename: string;
inputDir: string;
componentsDir?: string;
}): boolean;
interface MiniProgramComponents {
[name: string]: MiniProgramComponentsType;
}
export declare function findMiniProgramUsingComponents({ filename, inputDir, componentsDir, }: {
filename: string;
inputDir: string;
componentsDir?: string;
}): MiniProgramComponents;
export declare function findUsingComponentsJson(pathInpages: string, componentsDir: string): Record<any, any>;
export {};
+191
View File
@@ -0,0 +1,191 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.findUsingComponentsJson = exports.findMiniProgramUsingComponents = exports.isMiniProgramUsingComponent = exports.addMiniProgramUsingComponents = exports.addMiniProgramComponentJson = exports.addMiniProgramPageJson = exports.addMiniProgramAppJson = exports.findChangedJsonFiles = exports.normalizeJsonFilename = exports.findUsingComponents = exports.findJsonFile = exports.getComponentJsonFilenames = exports.hasJsonFile = exports.isMiniProgramPageSfcFile = exports.isMiniProgramPageFile = void 0;
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
const shared_1 = require("@vue/shared");
const utils_1 = require("../../utils");
const resolve_1 = require("../../resolve");
const utils_2 = require("../../vue/utils");
let appJsonCache = {};
const jsonFilesCache = new Map();
const jsonPagesCache = new Map();
const jsonComponentsCache = new Map();
const jsonUsingComponentsCache = new Map();
function isMiniProgramPageFile(file, inputDir) {
if (inputDir && path_1.default.isAbsolute(file)) {
file = (0, utils_1.normalizePath)(path_1.default.relative(inputDir, file));
}
return jsonPagesCache.has((0, utils_1.removeExt)(file));
}
exports.isMiniProgramPageFile = isMiniProgramPageFile;
function isMiniProgramPageSfcFile(file, inputDir) {
return (0, utils_2.isVueSfcFile)(file) && isMiniProgramPageFile(file, inputDir);
}
exports.isMiniProgramPageSfcFile = isMiniProgramPageSfcFile;
function hasJsonFile(filename) {
return (filename === 'app' ||
jsonPagesCache.has(filename) ||
jsonComponentsCache.has(filename));
}
exports.hasJsonFile = hasJsonFile;
function getComponentJsonFilenames() {
return [...jsonComponentsCache.keys()];
}
exports.getComponentJsonFilenames = getComponentJsonFilenames;
function findJsonFile(filename) {
if (filename === 'app') {
return appJsonCache;
}
return jsonPagesCache.get(filename) || jsonComponentsCache.get(filename);
}
exports.findJsonFile = findJsonFile;
function findUsingComponents(filename) {
return jsonUsingComponentsCache.get(filename);
}
exports.findUsingComponents = findUsingComponents;
function normalizeJsonFilename(filename) {
return (0, utils_1.normalizeNodeModules)(filename);
}
exports.normalizeJsonFilename = normalizeJsonFilename;
function findChangedJsonFiles(supportGlobalUsingComponents = true) {
const changedJsonFiles = new Map();
function findChangedFile(filename, json) {
const newJson = JSON.parse(JSON.stringify(json));
if (!newJson.usingComponents) {
newJson.usingComponents = {};
}
(0, shared_1.extend)(newJson.usingComponents, jsonUsingComponentsCache.get(filename));
// 格式化为相对路径,这样作为分包也可以直接运行
// app.json mp-baidu 在 win 不支持相对路径。所有平台改用绝对路径
if (filename !== 'app') {
let usingComponents = newJson.usingComponents;
// 如果小程序不支持 global 的 usingComponents
if (!supportGlobalUsingComponents) {
// 从取全局的 usingComponents 并补充到子组件 usingComponents 中
const globalUsingComponents = appJsonCache?.usingComponents || {};
const globalComponents = findUsingComponents('app') || {};
usingComponents = {
...globalUsingComponents,
...globalComponents,
...newJson.usingComponents,
};
}
Object.keys(usingComponents).forEach((name) => {
const componentFilename = usingComponents[name];
if (componentFilename.startsWith('/')) {
usingComponents[name] = (0, resolve_1.relativeFile)(filename, componentFilename.slice(1));
}
});
newJson.usingComponents = usingComponents;
}
const jsonStr = JSON.stringify(newJson, null, 2);
if (jsonFilesCache.get(filename) !== jsonStr) {
changedJsonFiles.set(filename, jsonStr);
jsonFilesCache.set(filename, jsonStr);
}
}
function findChangedFiles(jsonsCache) {
for (const name of jsonsCache.keys()) {
findChangedFile(name, jsonsCache.get(name));
}
}
findChangedFile('app', appJsonCache);
findChangedFiles(jsonPagesCache);
findChangedFiles(jsonComponentsCache);
return changedJsonFiles;
}
exports.findChangedJsonFiles = findChangedJsonFiles;
function addMiniProgramAppJson(appJson) {
appJsonCache = appJson;
}
exports.addMiniProgramAppJson = addMiniProgramAppJson;
function addMiniProgramPageJson(filename, json) {
jsonPagesCache.set(filename, json);
}
exports.addMiniProgramPageJson = addMiniProgramPageJson;
function addMiniProgramComponentJson(filename, json) {
jsonComponentsCache.set(filename, json);
}
exports.addMiniProgramComponentJson = addMiniProgramComponentJson;
function addMiniProgramUsingComponents(filename, json) {
jsonUsingComponentsCache.set(filename, json);
}
exports.addMiniProgramUsingComponents = addMiniProgramUsingComponents;
function isMiniProgramUsingComponent(name, options) {
return !!findMiniProgramUsingComponents(options)[name];
}
exports.isMiniProgramUsingComponent = isMiniProgramUsingComponent;
function findMiniProgramUsingComponents({ filename, inputDir, componentsDir, }) {
const globalUsingComponents = appJsonCache && appJsonCache.usingComponents;
const miniProgramComponents = {};
if (globalUsingComponents) {
(0, shared_1.extend)(miniProgramComponents, findMiniProgramUsingComponent(globalUsingComponents, componentsDir));
}
const jsonFile = findJsonFile((0, utils_1.removeExt)((0, utils_1.normalizeMiniProgramFilename)(filename, inputDir)));
if (jsonFile) {
if (jsonFile.usingComponents) {
(0, shared_1.extend)(miniProgramComponents, findMiniProgramUsingComponent(jsonFile.usingComponents, componentsDir));
}
// mp-baidu 特有
if (jsonFile.usingSwanComponents) {
(0, shared_1.extend)(miniProgramComponents, findMiniProgramUsingComponent(jsonFile.usingSwanComponents, componentsDir));
}
}
return miniProgramComponents;
}
exports.findMiniProgramUsingComponents = findMiniProgramUsingComponents;
function findMiniProgramUsingComponent(usingComponents, componentsDir) {
return Object.keys(usingComponents).reduce((res, name) => {
const path = usingComponents[name];
if (path.includes('plugin://')) {
// mp-weixin & mp-alipay
res[name] = 'plugin';
}
else if (path.includes('dynamicLib://')) {
// mp-baidu
res[name] = 'dynamicLib';
}
else if (path.includes('ext://')) {
// mp-toutiao
res[name] = 'ext';
}
else if (componentsDir &&
path.includes(componentsDir + '/') &&
findUsingComponentsJson(path, componentsDir).renderer === 'xr-frame') {
// mp-weixin & x-frame
res[name] = 'xr-frame';
}
else if (componentsDir && path.includes(componentsDir + '/')) {
res[name] = 'component';
}
return res;
}, {});
}
function findUsingComponentsJson(pathInpages, componentsDir) {
// 兼容test case
if (!process.env.UNI_INPUT_DIR)
return {};
let [, dir] = pathInpages.split(componentsDir);
if (dir === '') {
console.warn(`${pathInpages} 路径里没有找到对应的 ${componentsDir} 目录`);
return {};
}
dir = '.' + dir;
const fulldir = path_1.default.resolve(process.env.UNI_INPUT_DIR, componentsDir, dir);
let filename = path_1.default.parse(pathInpages).name + '.json';
let jsonPath = path_1.default.resolve(fulldir, filename);
if (fs_1.default.existsSync(jsonPath)) {
return require(jsonPath);
}
jsonPath = path_1.default.resolve(fulldir, 'index.json');
if (fs_1.default.existsSync(jsonPath)) {
return require(jsonPath);
}
console.warn(`${pathInpages} 路径下没有找到对应的json文件`);
return {};
}
exports.findUsingComponentsJson = findUsingComponentsJson;
+17
View File
@@ -0,0 +1,17 @@
import type { AppJson, NetworkTimeout, PageWindowOptions } from './types';
interface ParsePagesJsonOptions {
debug?: boolean;
darkmode?: boolean;
subpackages: boolean;
windowOptionsMap?: Record<string, string>;
tabBarOptionsMap?: Record<string, string>;
tabBarItemOptionsMap?: Record<string, string>;
networkTimeout?: NetworkTimeout;
}
export declare function parseMiniProgramPagesJson(jsonStr: string, platform: UniApp.PLATFORM, options?: ParsePagesJsonOptions): {
appJson: AppJson;
pageJsons: Record<string, PageWindowOptions>;
nvuePages: string[];
};
export declare function mergeMiniProgramAppJson(appJson: Record<string, any>, platformJson?: Record<string, any>, source?: Record<string, any>): void;
export {};
+157
View File
@@ -0,0 +1,157 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.mergeMiniProgramAppJson = exports.parseMiniProgramPagesJson = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const shared_1 = require("@vue/shared");
const json_1 = require("../json");
const pages_1 = require("../pages");
const utils_1 = require("./utils");
const utils_2 = require("../../utils");
const project_1 = require("./project");
const manifest_1 = require("../manifest");
const theme_1 = require("../theme");
const uni_x_1 = require("../uni-x");
function parseMiniProgramPagesJson(jsonStr, platform, options = { subpackages: false }) {
if (process.env.UNI_APP_X === 'true') {
// 目前仅对x开放
(0, uni_x_1.checkPagesJson)(jsonStr, process.env.UNI_INPUT_DIR);
}
return parsePagesJson(jsonStr, platform, options);
}
exports.parseMiniProgramPagesJson = parseMiniProgramPagesJson;
const NON_APP_JSON_KEYS = [
'unipush',
'secureNetwork',
'usingComponents',
'optimization',
'scopedSlotsCompiler',
'uniStatistics',
'mergeVirtualHostAttributes',
'styleIsolation',
];
function mergeMiniProgramAppJson(appJson, platformJson = {}, source = {}) {
Object.keys(source).forEach((key) => {
if (!project_1.projectKeys.includes(key)) {
project_1.projectKeys.push(key);
}
});
Object.keys(platformJson).forEach((name) => {
if (!(0, project_1.isMiniProgramProjectJsonKey)(name) &&
!NON_APP_JSON_KEYS.includes(name)) {
appJson[name] = platformJson[name];
}
});
}
exports.mergeMiniProgramAppJson = mergeMiniProgramAppJson;
function parsePagesJson(jsonStr, platform, { debug, darkmode, networkTimeout, subpackages, windowOptionsMap, tabBarOptionsMap, tabBarItemOptionsMap, } = {
subpackages: false,
}) {
let appJson = {
pages: [],
};
let pageJsons = {};
let nvuePages = [];
// preprocess
const pagesJson = (0, json_1.parseJson)(jsonStr, true);
if (!pagesJson) {
throw new Error(`[vite] Error: pages.json parse failed.\n`);
}
function addPageJson(pagePath, style) {
const filename = path_1.default.join(process.env.UNI_INPUT_DIR, pagePath);
if (fs_1.default.existsSync(filename + '.nvue') &&
!fs_1.default.existsSync(filename + '.vue')) {
nvuePages.push(pagePath);
}
const windowOptions = {};
if (platform === 'mp-baidu') {
// 仅百度小程序需要页面配置 component:true
// 快手小程序反而不能配置 component:true,故不能统一添加,目前硬编码处理
windowOptions.component = true;
}
pageJsons[pagePath] = (0, shared_1.extend)(windowOptions, (0, utils_1.parseWindowOptions)(style, platform, windowOptionsMap));
}
// pages
(0, pages_1.validatePages)(pagesJson, jsonStr);
pagesJson.pages.forEach((page) => {
appJson.pages.push(page.path);
addPageJson(page.path, page.style);
});
// subpackages
pagesJson.subPackages = pagesJson.subPackages || pagesJson.subpackages;
if (pagesJson.subPackages) {
if (subpackages) {
appJson.subPackages = pagesJson.subPackages.map(({ root, pages, ...rest }) => {
return (0, shared_1.extend)({
root,
pages: pages.map((page) => {
addPageJson((0, utils_2.normalizePath)(path_1.default.join(root, page.path)), page.style);
return page.path;
}),
}, rest);
});
}
else {
pagesJson.subPackages.forEach(({ root, pages }) => {
pages.forEach((page) => {
const pagePath = (0, utils_2.normalizePath)(path_1.default.join(root, page.path));
appJson.pages.push(pagePath);
addPageJson(pagePath, page.style);
});
});
}
}
// window
if (pagesJson.globalStyle) {
const windowOptions = (0, utils_1.parseWindowOptions)(pagesJson.globalStyle, platform, windowOptionsMap);
const { usingComponents } = windowOptions;
if (usingComponents) {
delete windowOptions.usingComponents;
appJson.usingComponents = usingComponents;
}
else {
delete appJson.usingComponents;
}
appJson.window = windowOptions;
}
// tabBar
if (pagesJson.tabBar) {
const tabBar = (0, utils_1.parseTabBar)(pagesJson.tabBar, platform, tabBarOptionsMap, tabBarItemOptionsMap);
if (tabBar) {
appJson.tabBar = tabBar;
}
}
(0, pages_1.filterPlatformPages)(platform, pagesJson);
['preloadRule', 'workers', 'plugins', 'entryPagePath'].forEach((name) => {
if ((0, shared_1.hasOwn)(pagesJson, name)) {
appJson[name] = pagesJson[name];
}
});
if (debug) {
appJson.debug = debug;
}
if (networkTimeout) {
appJson.networkTimeout = networkTimeout;
}
const manifestJson = (0, manifest_1.getPlatformManifestJsonOnce)();
if (!darkmode) {
const { pages, window, tabBar } = (0, theme_1.initTheme)(manifestJson, appJson);
(0, shared_1.extend)(appJson, JSON.parse(JSON.stringify({ pages, window, tabBar })));
delete appJson.darkmode;
delete appJson.themeLocation;
pageJsons = (0, theme_1.initTheme)(manifestJson, pageJsons);
}
else {
const themeLocation = manifestJson.themeLocation || 'theme.json';
if ((0, theme_1.hasThemeJson)(path_1.default.join(process.env.UNI_INPUT_DIR, themeLocation)))
appJson.themeLocation = themeLocation;
}
return {
appJson,
pageJsons,
nvuePages,
};
}
+15
View File
@@ -0,0 +1,15 @@
interface ParseMiniProgramProjectJsonOptions {
template: Record<string, any>;
pagesJson: UniApp.PagesJson;
}
interface ProjectConfig {
appid: string;
projectname: string;
condition?: {
miniprogram?: UniApp.PagesJson['condition'];
};
}
export declare const projectKeys: string[];
export declare function isMiniProgramProjectJsonKey(name: string): boolean;
export declare function parseMiniProgramProjectJson(jsonStr: string, platform: UniApp.PLATFORM, { template, pagesJson }: ParseMiniProgramProjectJsonOptions): ProjectConfig;
export {};
+117
View File
@@ -0,0 +1,117 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseMiniProgramProjectJson = exports.isMiniProgramProjectJsonKey = exports.projectKeys = void 0;
const shared_1 = require("@vue/shared");
const merge_1 = require("merge");
const json_1 = require("../json");
exports.projectKeys = [
'appid',
'setting',
'miniprogramRoot',
'cloudfunctionRoot',
'qcloudRoot',
'pluginRoot',
'compileType',
'libVersion',
'projectname',
'packOptions',
'debugOptions',
'scripts',
'cloudbaseRoot',
];
function isMiniProgramProjectJsonKey(name) {
return exports.projectKeys.includes(name);
}
exports.isMiniProgramProjectJsonKey = isMiniProgramProjectJsonKey;
function parseMiniProgramProjectJson(jsonStr, platform, { template, pagesJson }) {
const projectJson = JSON.parse(JSON.stringify(template));
const manifestJson = (0, json_1.parseJson)(jsonStr);
if (manifestJson) {
projectJson.projectname = manifestJson.name;
// 用户的平台配置
const platformConfig = manifestJson[platform];
if (platformConfig) {
const setProjectJson = (name) => {
if ((0, shared_1.hasOwn)(platformConfig, name)) {
if ((0, shared_1.isPlainObject)(platformConfig[name]) &&
(0, shared_1.isPlainObject)(projectJson[name])) {
;
projectJson[name] = (0, merge_1.recursive)(true, projectJson[name], platformConfig[name]);
}
else {
;
projectJson[name] = platformConfig[name];
}
}
};
// 读取 template 中的配置
Object.keys(template).forEach((name) => {
if (!exports.projectKeys.includes(name)) {
exports.projectKeys.push(name);
}
});
// common mp config
exports.projectKeys.forEach((name) => {
setProjectJson(name);
});
// 使用了微信小程序手势系统,自动开启 ES6=>ES5
platform === 'mp-weixin' &&
weixinSkyline(platformConfig) &&
openES62ES5(projectJson);
}
}
// 其实仅开发期间 condition 生效即可,暂不做判断
const miniprogram = parseMiniProgramCondition(pagesJson);
if (miniprogram) {
if (!projectJson.condition) {
projectJson.condition = {};
}
projectJson.condition.miniprogram = miniprogram;
}
// appid
if (!projectJson.appid) {
projectJson.appid = 'touristappid';
}
return projectJson;
}
exports.parseMiniProgramProjectJson = parseMiniProgramProjectJson;
function weixinSkyline(config) {
return (config.renderer === 'skyline' &&
config.lazyCodeLoading === 'requiredComponents');
}
function openES62ES5(config) {
if (!config.setting) {
config.setting = {};
}
if (!config.setting.es6) {
config.setting.es6 = true;
}
}
function parseMiniProgramCondition(pagesJson) {
const launchPagePath = process.env.UNI_CLI_LAUNCH_PAGE_PATH || '';
if (launchPagePath) {
return {
current: 0,
list: [
{
id: 0,
name: launchPagePath, // 模式名称
pathName: launchPagePath, // 启动页面,必选
query: process.env.UNI_CLI_LAUNCH_PAGE_QUERY || '', // 启动参数,在页面的onLoad函数里面得到。
},
],
};
}
const condition = pagesJson.condition;
if (!condition || !(0, shared_1.isArray)(condition.list) || !condition.list.length) {
return;
}
condition.list.forEach(function (item, index) {
item.id = item.id || index;
if (item.path) {
item.pathName = item.path;
delete item.path;
}
});
return condition;
}
+123
View File
@@ -0,0 +1,123 @@
export interface ComponentJson {
component: true;
usingComponents?: UsingComponents;
usingSwanComponents?: UsingComponents;
styleIsolation?: 'apply-shared' | 'shared' | 'isolated';
}
interface ShareWindowOptions {
navigationBarBackgroundColor?: string;
navigationBarTextStyle?: 'white' | 'black';
navigationBarTitleText?: string;
navigationStyle?: 'default' | 'custom';
backgroundColor?: string;
backgroundTextStyle?: 'dark' | 'light';
backgroundColorTop?: string;
backgroundColorBottom?: string;
enablePullDownRefresh?: boolean;
onReachBottomDistance?: number;
pageOrientation?: 'portrait' | 'landscape' | 'auto';
}
type Style = 'v2' | string;
type RestartStrategy = 'homePage' | 'homePageAndLatestPage' | string;
export interface PageWindowOptions extends ShareWindowOptions {
component?: true;
disableScroll?: boolean;
usingComponents?: UsingComponents;
usingSwanComponents?: UsingComponents;
initialRenderingCache?: 'static' | string;
style?: Style;
singlePage?: SinglePage;
restartStrategy?: RestartStrategy;
}
export interface AppWindowOptions extends ShareWindowOptions {
visualEffectInBackground?: 'none' | 'hidden';
}
interface SubPackage {
name?: string;
root: string;
pages: string[];
independent?: boolean;
}
interface TabBarItem {
pagePath: string;
text: string;
iconPath?: string;
selectedIconPath?: string;
}
export interface TabBar {
color: string;
selectedColor: string;
backgroundColor: string;
borderStyle?: 'black' | 'white';
list: TabBarItem[];
position?: 'bottom' | 'top';
custom?: boolean;
}
export interface NetworkTimeout {
request?: number;
requeconnectSocketst?: number;
uploadFile?: number;
downloadFile?: number;
}
interface Plugins {
[name: string]: {
version: string;
provider: string;
};
}
interface PreloadRule {
[name: string]: {
network: 'wifi' | 'all';
packages: string[];
};
}
export interface UsingComponents {
[name: string]: string;
}
interface Permission {
[name: string]: {
desc: string;
};
}
interface UseExtendedLib {
kbone: boolean;
weui: boolean;
}
interface EntranceDeclare {
locationMessage: {
path: string;
query: string;
};
}
interface SinglePage {
navigationBarFit?: 'squeezed' | 'float';
}
export interface AppJson {
entryPagePath?: string;
pages: string[];
window?: AppWindowOptions;
tabBar?: TabBar;
networkTimeout?: NetworkTimeout;
debug?: boolean;
functionalPages?: boolean;
subPackages?: SubPackage[];
workers?: string;
requiredBackgroundModes?: string[];
plugins?: Plugins;
preloadRule?: PreloadRule;
resizable?: boolean;
usingComponents?: UsingComponents;
permission?: Permission;
sitemapLocation?: string;
style?: Style;
useExtendedLib?: UseExtendedLib;
entranceDeclare?: EntranceDeclare;
darkmode?: boolean;
themeLocation?: string;
lazyCodeLoading?: 'requiredComponents' | string;
singlePage?: SinglePage;
restartStrategy?: RestartStrategy;
[name: string]: unknown;
}
export type MiniProgramComponentsType = 'plugin' | 'component' | 'dynamicLib' | 'ext' | 'xr-frame';
export {};
+2
View File
@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
+3
View File
@@ -0,0 +1,3 @@
import type { AppWindowOptions, PageWindowOptions, TabBar } from './types';
export declare function parseWindowOptions(style: UniApp.PagesJsonPageStyle, platform: UniApp.PLATFORM, windowOptionsMap?: Record<string, string>): PageWindowOptions | AppWindowOptions;
export declare function parseTabBar(tabBar: UniApp.TabBarOptions, platform: UniApp.PLATFORM, tabBarOptionsMap?: Record<string, string>, tabBarItemOptionsMap?: Record<string, string>): TabBar;
+66
View File
@@ -0,0 +1,66 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseTabBar = exports.parseWindowOptions = void 0;
const shared_1 = require("@vue/shared");
const pages_1 = require("../pages");
function trimJson(json) {
delete json.maxWidth;
delete json.topWindow;
delete json.leftWindow;
delete json.rightWindow;
if (json.tabBar) {
delete json.tabBar.matchMedia;
}
return json;
}
function convert(to, from, map) {
Object.keys(map).forEach((key) => {
if ((0, shared_1.hasOwn)(from, map[key])) {
to[key] = from[map[key]];
}
});
return to;
}
function parseWindowOptions(style, platform, windowOptionsMap) {
if (!style) {
return {};
}
const platformStyle = style[platform] || {};
(0, pages_1.removePlatformStyle)(trimJson(style));
const res = {};
if (windowOptionsMap) {
return (0, shared_1.extend)(convert(res, style, windowOptionsMap), platformStyle);
}
return (0, shared_1.extend)(res, style, platformStyle);
}
exports.parseWindowOptions = parseWindowOptions;
function trimTabBarJson(tabBar) {
;
[
'fontSize',
'height',
'iconWidth',
'midButton',
'selectedIndex',
'spacing',
].forEach((name) => {
delete tabBar[name];
});
return tabBar;
}
function parseTabBar(tabBar, platform, tabBarOptionsMap, tabBarItemOptionsMap) {
const platformStyle = tabBar[platform] || {};
(0, pages_1.removePlatformStyle)(trimTabBarJson(tabBar));
const res = {};
if (tabBarOptionsMap) {
if (tabBarItemOptionsMap && tabBar.list) {
tabBar.list = tabBar.list.map((item) => {
return convert({}, item, tabBarItemOptionsMap);
});
}
convert(res, tabBar, tabBarOptionsMap);
return (0, shared_1.extend)(res, platformStyle);
}
return (0, shared_1.extend)(res, tabBar, platformStyle);
}
exports.parseTabBar = parseTabBar;
+32
View File
@@ -0,0 +1,32 @@
export declare function isUniPageFile(file: string, inputDir?: string): boolean;
export declare function isUniPageSetupAndTs(file: string): boolean;
export declare function isUniPageSfcFile(file: string, inputDir?: string): boolean;
/**
* 小程序平台慎用,因为该解析不支持 subpackages
* @param inputDir
* @param platform
* @param normalize
* @returns
*/
export declare const parsePagesJson: (inputDir: string, platform: UniApp.PLATFORM, normalize?: boolean) => UniApp.PagesJson;
/**
* 该方法解析出来的是不支持 subpackages,会被合并入 pages
*/
export declare const parsePagesJsonOnce: (inputDir: string, platform: UniApp.PLATFORM, normalize?: boolean) => UniApp.PagesJson;
/**
* 目前 App 和 H5 使用了该方法
* @param jsonStr
* @param platform
* @param param2
* @returns
*/
export declare function normalizePagesJson(jsonStr: string, platform: UniApp.PLATFORM, { subpackages, }?: {
subpackages: boolean;
}): UniApp.PagesJson;
export declare function validatePages(pagesJson: Record<string, any>, jsonStr: string): void;
export declare function removePlatformStyle(pageStyle: Record<string, any>): Record<string, any>;
export declare function normalizePagesRoute(pagesJson: UniApp.PagesJson): UniApp.UniRoute[];
declare function parseSubpackagesRoot(inputDir: string, platform: UniApp.PLATFORM): string[];
export declare const parseSubpackagesRootOnce: typeof parseSubpackagesRoot;
export declare function filterPlatformPages(platform: UniApp.PLATFORM, pagesJson: UniApp.PagesJson): void;
export {};
+525
View File
@@ -0,0 +1,525 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.filterPlatformPages = exports.parseSubpackagesRootOnce = exports.normalizePagesRoute = exports.removePlatformStyle = exports.validatePages = exports.normalizePagesJson = exports.parsePagesJsonOnce = exports.parsePagesJson = exports.isUniPageSfcFile = exports.isUniPageSetupAndTs = exports.isUniPageFile = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const shared_1 = require("@vue/shared");
const uni_shared_1 = require("@dcloudio/uni-shared");
const utils_1 = require("../utils");
const json_1 = require("./json");
const utils_2 = require("../vue/utils");
const vite_1 = require("../vite");
const constants_1 = require("../constants");
const theme_1 = require("./theme");
const manifest_1 = require("./manifest");
const pagesCacheSet = new Set();
function isUniPageFile(file, inputDir = process.env.UNI_INPUT_DIR) {
if (inputDir && path_1.default.isAbsolute(file)) {
file = (0, utils_1.normalizePath)(path_1.default.relative(inputDir, file));
}
return pagesCacheSet.has((0, utils_1.removeExt)(file));
}
exports.isUniPageFile = isUniPageFile;
function isUniPageSetupAndTs(file) {
const { filename, query } = (0, vite_1.parseVueRequest)(file);
return !!(query.vue &&
query.setup &&
(0, shared_1.hasOwn)(query, 'lang.ts') &&
constants_1.EXTNAME_VUE_RE.test(filename));
}
exports.isUniPageSetupAndTs = isUniPageSetupAndTs;
function isUniPageSfcFile(file, inputDir = process.env.UNI_INPUT_DIR) {
return (0, utils_2.isVueSfcFile)(file) && isUniPageFile(file, inputDir);
}
exports.isUniPageSfcFile = isUniPageSfcFile;
/**
* 小程序平台慎用,因为该解析不支持 subpackages
* @param inputDir
* @param platform
* @param normalize
* @returns
*/
const parsePagesJson = (inputDir, platform, normalize = true) => {
const pagesFilename = path_1.default.join(inputDir, 'pages.json');
if (!fs_1.default.existsSync(pagesFilename)) {
if (!(0, utils_1.isNormalCompileTarget)()) {
return {
pages: [],
globalStyle: { navigationBar: {} },
};
}
}
const jsonStr = fs_1.default.readFileSync(pagesFilename, 'utf8');
if (normalize) {
return normalizePagesJson(jsonStr, platform);
}
return (0, json_1.parseJson)(jsonStr, true);
};
exports.parsePagesJson = parsePagesJson;
/**
* 该方法解析出来的是不支持 subpackages,会被合并入 pages
*/
exports.parsePagesJsonOnce = (0, uni_shared_1.once)(exports.parsePagesJson);
/**
* 目前 App 和 H5 使用了该方法
* @param jsonStr
* @param platform
* @param param2
* @returns
*/
function normalizePagesJson(jsonStr, platform, { subpackages, } = { subpackages: false }) {
let pagesJson = {
pages: [],
globalStyle: {
navigationBar: {},
},
};
// preprocess
try {
pagesJson = (0, json_1.parseJson)(jsonStr, true);
}
catch (e) {
console.error(`[vite] Error: pages.json parse failed.\n`, jsonStr, e);
}
// pages
validatePages(pagesJson, jsonStr);
pagesJson.subPackages = pagesJson.subPackages || pagesJson.subpackages;
delete pagesJson.subpackages;
// subpackages
if (pagesJson.subPackages) {
if (subpackages) {
pagesJson.subPackages.forEach(({ pages }) => {
pages && normalizePages(pages, platform);
});
}
else {
pagesJson.pages.push(...normalizeSubpackages(pagesJson.subPackages));
delete pagesJson.subPackages;
}
}
else {
delete pagesJson.subPackages;
}
// pageStyle
normalizePages(pagesJson.pages, platform);
// globalStyle
pagesJson.globalStyle = normalizePageStyle(null, pagesJson.globalStyle, platform);
// tabBar
if (pagesJson.tabBar) {
const tabBar = normalizeTabBar(pagesJson.tabBar, platform);
if (tabBar) {
pagesJson.tabBar = tabBar;
}
else {
delete pagesJson.tabBar;
}
}
// 过滤平台page
filterPlatformPages(platform, pagesJson);
// 缓存页面列表
pagesCacheSet.clear();
pagesJson.pages.forEach((page) => pagesCacheSet.add(page.path));
const manifestJsonPlatform = (0, manifest_1.getPlatformManifestJsonOnce)();
if (!manifestJsonPlatform.darkmode) {
const { pages, globalStyle, tabBar } = (0, theme_1.initTheme)(manifestJsonPlatform, pagesJson);
(0, shared_1.extend)(pagesJson, { pages, globalStyle, tabBar });
}
return pagesJson;
}
exports.normalizePagesJson = normalizePagesJson;
function validatePages(pagesJson, jsonStr) {
if (!(0, shared_1.isArray)(pagesJson.pages)) {
pagesJson.pages = [];
console.error(`[uni-app] Error: pages.json->pages parse failed.`);
process.exit(0);
}
else if (!pagesJson.pages.length) {
console.error(`[uni-app] Error: pages.json->pages must contain at least 1 page.`);
process.exit(0);
}
else {
const pages = [];
pagesJson.pages.forEach((page) => {
if (pages.indexOf(page.path) !== -1) {
console.error(`[uni-app] Error: pages.json->${page.path} duplication.`);
process.exit(0);
}
pages.push(page.path);
});
}
}
exports.validatePages = validatePages;
function normalizePages(pages, platform) {
pages.forEach((page) => {
page.style = normalizePageStyle(page.path, page.style, platform);
if (platform === 'app-harmony') {
// 鸿蒙下强制 isNVue 为 false,增加额外的 isNVueStyle 来标记样式处理
// 因为已有的代码里太多根据 isNVue 来处理的逻辑,这些逻辑在鸿蒙都不适用
// 鸿蒙仅需要将 nvue 当做 vue,并补充 css 即可
if (page.style.isNVue) {
page.style.isNVue = false;
page.style.isNVueStyle = true;
}
}
});
if (platform !== 'app') {
return;
}
const subNVuePages = [];
// subNVues
pages.forEach(({ style: { subNVues } }) => {
if (!(0, shared_1.isArray)(subNVues)) {
return;
}
subNVues.forEach((subNVue) => {
if (subNVue && subNVue.path) {
subNVuePages.push({
path: subNVue.path,
style: { isSubNVue: true, isNVue: true, navigationBar: {} },
});
}
});
});
if (subNVuePages.length) {
pages.push(...subNVuePages);
}
}
function normalizeSubpackages(subpackages) {
const pages = [];
if ((0, shared_1.isArray)(subpackages)) {
subpackages.forEach(({ root, pages: subPages }) => {
if (root && subPages.length) {
subPages.forEach((subPage) => {
subPage.path = (0, utils_1.normalizePath)(path_1.default.join(root, subPage.path));
subPage.style = normalizeSubpackageSubNVues(root, subPage.style);
pages.push(subPage);
});
}
});
}
return pages;
}
function normalizeSubpackageSubNVues(root, style = { navigationBar: {} }) {
const platformStyle = style['app'] || style['app-plus'];
if (!platformStyle) {
return style;
}
if ((0, shared_1.isArray)(platformStyle.subNVues)) {
platformStyle.subNVues.forEach((subNVue) => {
if (subNVue.path) {
subNVue.path = (0, utils_1.normalizePath)(path_1.default.join(root, subNVue.path));
}
});
}
return style;
}
function normalizePageStyle(pagePath, pageStyle, platform) {
let isNVue = false;
if (process.env.UNI_APP_X === 'true') {
isNVue = undefined;
}
else {
const hasNVue = pagePath &&
process.env.UNI_INPUT_DIR &&
fs_1.default.existsSync(path_1.default.join(process.env.UNI_INPUT_DIR, pagePath + '.nvue'))
? true
: undefined;
if (hasNVue) {
const hasVue = fs_1.default.existsSync(path_1.default.join(process.env.UNI_INPUT_DIR, pagePath + '.vue'));
if (hasVue) {
if (platform === 'app') {
if (process.env.UNI_NVUE_COMPILER !== 'vue') {
isNVue = true;
}
}
}
else {
isNVue = true;
}
}
}
if (pageStyle) {
if (platform === 'h5') {
(0, shared_1.extend)(pageStyle, pageStyle['app'] || pageStyle['app-plus'], pageStyle['web'] || pageStyle['h5']);
}
else if (platform === 'app') {
(0, shared_1.extend)(pageStyle, pageStyle['app'] || pageStyle['app-plus']);
}
else {
(0, shared_1.extend)(pageStyle, pageStyle[platform]);
}
if (['h5', 'app', 'app-harmony'].includes(platform)) {
pageStyle.navigationBar = normalizeNavigationBar(pageStyle);
if (isEnablePullDownRefresh(pageStyle)) {
pageStyle.enablePullDownRefresh = true;
pageStyle.pullToRefresh = normalizePullToRefresh(pageStyle);
}
if (platform === 'app') {
pageStyle.disableSwipeBack === true
? (pageStyle.popGesture = 'none')
: delete pageStyle.popGesture;
delete pageStyle.disableSwipeBack;
}
}
pageStyle.isNVue = isNVue;
removePlatformStyle(pageStyle);
return pageStyle;
}
return { navigationBar: {}, isNVue };
}
const navigationBarMaps = {
navigationBarBackgroundColor: 'backgroundColor',
navigationBarTextStyle: 'textStyle',
navigationBarTitleText: 'titleText',
navigationStyle: 'style',
titleImage: 'titleImage',
titlePenetrate: 'titlePenetrate',
transparentTitle: 'transparentTitle',
};
function normalizeNavigationBar(pageStyle) {
const navigationBar = Object.create(null);
Object.keys(navigationBarMaps).forEach((name) => {
if ((0, shared_1.hasOwn)(pageStyle, name)) {
navigationBar[navigationBarMaps[name]] =
pageStyle[name];
delete pageStyle[name];
}
});
navigationBar.type = navigationBar.type || 'default';
const { titleNView } = pageStyle;
if ((0, shared_1.isPlainObject)(titleNView)) {
(0, shared_1.extend)(navigationBar, titleNView);
delete pageStyle.titleNView;
}
else if (titleNView === false) {
navigationBar.style = 'custom';
}
if ((0, shared_1.hasOwn)(navigationBar, 'transparentTitle')) {
const transparentTitle = navigationBar.transparentTitle;
if (transparentTitle === 'always') {
navigationBar.style = 'custom';
navigationBar.type = 'float';
}
else if (transparentTitle === 'auto') {
navigationBar.type = 'transparent';
}
else {
navigationBar.type = 'default';
}
delete navigationBar.transparentTitle;
}
if (navigationBar.titleImage && navigationBar.titleText) {
delete navigationBar.titleText;
}
if (!navigationBar.titleColor && (0, shared_1.hasOwn)(navigationBar, 'textStyle')) {
const textStyle = navigationBar.textStyle;
if (constants_1.TEXT_STYLE.includes(textStyle)) {
navigationBar.titleColor = (0, uni_shared_1.normalizeTitleColor)(textStyle);
}
else {
navigationBar.titleColor = navigationBar.textStyle;
}
delete navigationBar.textStyle;
}
if (pageStyle.navigationBarShadow &&
pageStyle.navigationBarShadow.colorType) {
navigationBar.shadowColorType = pageStyle.navigationBarShadow.colorType;
delete pageStyle.navigationBarShadow;
}
const parsedNavigationBar = (0, theme_1.initTheme)((0, manifest_1.getPlatformManifestJsonOnce)(), navigationBar);
if ((0, shared_1.isArray)(navigationBar.buttons)) {
navigationBar.buttons = navigationBar.buttons.map((btn) => normalizeNavigationBarButton(btn, navigationBar.type, parsedNavigationBar.titleColor));
}
if ((0, shared_1.isPlainObject)(navigationBar.searchInput)) {
navigationBar.searchInput = normalizeNavigationBarSearchInput(navigationBar.searchInput);
}
if (navigationBar.type === 'transparent') {
navigationBar.coverage = navigationBar.coverage || '132px';
}
return navigationBar;
}
function normalizeNavigationBarButton(btn, type, titleColor) {
btn.color = btn.color || titleColor;
if (!btn.fontSize) {
btn.fontSize =
type === 'transparent' || (btn.text && /\\u/.test(btn.text))
? '22px'
: '27px';
}
else if (/\d$/.test(btn.fontSize)) {
btn.fontSize += 'px';
}
btn.text = btn.text || '';
return btn;
}
function normalizeNavigationBarSearchInput(searchInput) {
return (0, shared_1.extend)({
autoFocus: false,
align: 'center',
color: '#000',
backgroundColor: 'rgba(255,255,255,0.5)',
borderRadius: '0px',
placeholder: '',
placeholderColor: '#CCCCCC',
disabled: false,
}, searchInput);
}
const DEFAULT_TAB_BAR = {
position: 'bottom',
color: '#999',
selectedColor: '#007aff',
borderStyle: 'black',
blurEffect: 'none',
fontSize: '10px',
iconWidth: '24px',
spacing: '3px',
height: uni_shared_1.TABBAR_HEIGHT + 'px',
list: [],
};
function normalizeTabBar(tabBar, platform) {
const { midButton } = tabBar;
tabBar = (0, shared_1.extend)({}, DEFAULT_TAB_BAR, tabBar);
tabBar.list.forEach((item) => {
if (item.iconPath) {
item.iconPath = normalizeFilepath(item.iconPath);
}
if (item.selectedIconPath) {
item.selectedIconPath = normalizeFilepath(item.selectedIconPath);
}
});
if (midButton && midButton.backgroundImage) {
midButton.backgroundImage = normalizeFilepath(midButton.backgroundImage);
}
tabBar.selectedIndex = 0;
tabBar.shown = true;
return tabBar;
}
const SCHEME_RE = /^([a-z-]+:)?\/\//i;
const DATA_RE = /^data:.*,.*/;
function normalizeFilepath(filepath) {
const themeConfig = (0, theme_1.normalizeThemeConfigOnce)()['light'] || {};
if (themeConfig[filepath.replace('@', '')])
return filepath;
if (!(SCHEME_RE.test(filepath) || DATA_RE.test(filepath)) &&
filepath.indexOf('/') !== 0) {
return (0, uni_shared_1.addLeadingSlash)(filepath);
}
return filepath;
}
const platforms = ['h5', 'app', 'mp-', 'quickapp', 'web'];
function removePlatformStyle(pageStyle) {
Object.keys(pageStyle).forEach((name) => {
if (platforms.find((prefix) => name.startsWith(prefix))) {
delete pageStyle[name];
}
});
return pageStyle;
}
exports.removePlatformStyle = removePlatformStyle;
function normalizePagesRoute(pagesJson) {
const firstPagePath = pagesJson.pages[0].path;
const tabBarList = (pagesJson.tabBar && pagesJson.tabBar.list) || [];
return pagesJson.pages.map((pageOptions) => {
const pagePath = pageOptions.path;
const isEntry = firstPagePath === pagePath ? true : undefined;
const tabBarIndex = tabBarList.findIndex((tabBarPage) => tabBarPage.pagePath === pagePath);
const isTabBar = tabBarIndex !== -1 ? true : undefined;
let windowTop = 0;
const meta = (0, shared_1.extend)({
isQuit: isEntry || isTabBar ? true : undefined,
isEntry: isEntry || undefined,
isTabBar: isTabBar || undefined,
tabBarIndex: isTabBar ? tabBarIndex : undefined,
windowTop: windowTop || undefined,
}, pageOptions.style);
return {
path: pageOptions.path,
meta,
};
});
}
exports.normalizePagesRoute = normalizePagesRoute;
function isEnablePullDownRefresh(pageStyle) {
return pageStyle.enablePullDownRefresh || pageStyle.pullToRefresh?.support;
}
function normalizePullToRefresh(pageStyle) {
return pageStyle.pullToRefresh;
}
function parseSubpackagesRoot(inputDir, platform) {
const pagesJson = (0, exports.parsePagesJson)(inputDir, platform, false);
const subpackages = pagesJson.subPackages || pagesJson.subpackages;
const roots = [];
if ((0, shared_1.isArray)(subpackages)) {
subpackages.forEach(({ root }) => {
if (root) {
roots.push(root);
}
});
}
return roots;
}
exports.parseSubpackagesRootOnce = (0, uni_shared_1.once)(parseSubpackagesRoot);
let isInvalidPagesWarned = false;
function filterPlatformPages(platform, pagesJson) {
const invalidPages = [];
pagesJson.pages = pagesJson.pages.filter(({ path }) => {
if (isPlatformPage(platform, path)) {
return true;
}
invalidPages.push(path);
return false;
});
if (pagesJson.subPackages) {
pagesJson.subPackages.forEach((subPackage) => {
if (subPackage.pages) {
subPackage.pages = subPackage.pages.filter(({ path }) => {
const pagePath = subPackage.root + '/' + path;
if (isPlatformPage(platform, pagePath)) {
return true;
}
invalidPages.push(pagePath);
return false;
});
}
});
}
if (pagesJson.subpackages) {
pagesJson.subpackages.forEach((subPackage) => {
if (subPackage.pages) {
subPackage.pages = subPackage.pages.filter(({ path }) => {
const pagePath = subPackage.root + '/' + path;
if (isPlatformPage(platform, pagePath)) {
return true;
}
invalidPages.push(pagePath);
return false;
});
}
});
}
// 目前仅启动的时候警告一次,该方法可能会被调用很多次
if (invalidPages.length) {
if (!isInvalidPagesWarned) {
isInvalidPagesWarned = true;
console.log(`已忽略页面:${invalidPages.join('、')}。详见:https://uniapp.dcloud.net.cn/tutorial/platform.html#platforms`);
}
}
}
exports.filterPlatformPages = filterPlatformPages;
function isPlatformPage(platform, pagePath) {
if (pagePath.startsWith('platforms/')) {
if (platform === 'app' || platform === 'app-plus') {
return (pagePath.startsWith('platforms/app/') ||
pagePath.startsWith('platforms/app-plus/'));
}
else if (platform === 'h5' || platform === 'web') {
return (pagePath.startsWith('platforms/h5/') ||
pagePath.startsWith('platforms/web/'));
}
return pagePath.startsWith('platforms/' + platform + '/');
}
return true;
}
+23
View File
@@ -0,0 +1,23 @@
export declare function hasThemeJson(themeLocation: string): boolean;
export declare const parseThemeJson: (themeLocation?: string) => UniApp.ThemeJson;
export declare const normalizeThemeConfigOnce: (manifestJsonPlatform?: Record<string, any>) => UniApp.ThemeJson;
export declare function initTheme<T extends object>(manifestJson: Record<string, any>, pagesJson: T): T;
export declare class ThemeSassParser {
_index: number;
_input: string;
_theme: Record<string, Record<string, any>>;
constructor();
parse(input: string): Record<string, Record<string, any>>;
parseVariable(): void;
parseVariableValue(): any;
parseFunction(): void | string[];
skipOtherValue(): void;
parseString(): string;
pushThemeValue(key: string, valuePair: string[]): void;
consume(expected: string): void;
get currentChar(): string;
skipWhiteSpaceAndComments(): void;
skipComment(): void;
skipWhiteSpace(): void;
isspace(str: string): boolean;
}

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