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.
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+615
View File
@@ -0,0 +1,615 @@
import { isArray, hasOwn, isString, isPlainObject, isObject, toRawType, capitalize, makeMap, isFunction, isPromise, extend, remove } from '@vue/shared';
function validateProtocolFail(name, msg) {
console.warn(`${name}: ${msg}`);
}
function validateProtocol(name, data, protocol, onFail) {
if (!onFail) {
onFail = validateProtocolFail;
}
for (const key in protocol) {
const errMsg = validateProp(key, data[key], protocol[key], !hasOwn(data, key));
if (isString(errMsg)) {
onFail(name, errMsg);
}
}
}
function validateProtocols(name, args, protocol, onFail) {
if (!protocol) {
return;
}
if (!isArray(protocol)) {
return validateProtocol(name, args[0] || Object.create(null), protocol, onFail);
}
const len = protocol.length;
const argsLen = args.length;
for (let i = 0; i < len; i++) {
const opts = protocol[i];
const data = Object.create(null);
if (argsLen > i) {
data[opts.name] = args[i];
}
validateProtocol(name, data, { [opts.name]: opts }, onFail);
}
}
function validateProp(name, value, prop, isAbsent) {
if (!isPlainObject(prop)) {
prop = { type: prop };
}
const { type, required, validator } = prop;
// required!
if (required && isAbsent) {
return 'Missing required args: "' + name + '"';
}
// missing but optional
if (value == null && !required) {
return;
}
// type check
if (type != null) {
let isValid = false;
const types = isArray(type) ? type : [type];
const expectedTypes = [];
// value is valid as long as one of the specified types match
for (let i = 0; i < types.length && !isValid; i++) {
const { valid, expectedType } = assertType(value, types[i]);
expectedTypes.push(expectedType || '');
isValid = valid;
}
if (!isValid) {
return getInvalidTypeMessage(name, value, expectedTypes);
}
}
// custom validator
if (validator) {
return validator(value);
}
}
const isSimpleType = /*#__PURE__*/ makeMap('String,Number,Boolean,Function,Symbol');
function assertType(value, type) {
let valid;
const expectedType = getType(type);
if (isSimpleType(expectedType)) {
const t = typeof value;
valid = t === expectedType.toLowerCase();
// for primitive wrapper objects
if (!valid && t === 'object') {
valid = value instanceof type;
}
}
else if (expectedType === 'Object') {
valid = isObject(value);
}
else if (expectedType === 'Array') {
valid = isArray(value);
}
else {
if (__PLATFORM__ === 'app') {
// App平台ArrayBuffer等参数跨实例传输,无法通过 instanceof 识别
valid = value instanceof type || toRawType(value) === getType(type);
}
else {
valid = value instanceof type;
}
}
return {
valid,
expectedType,
};
}
function getInvalidTypeMessage(name, value, expectedTypes) {
let message = `Invalid args: type check failed for args "${name}".` +
` Expected ${expectedTypes.map(capitalize).join(', ')}`;
const expectedType = expectedTypes[0];
const receivedType = toRawType(value);
const expectedValue = styleValue(value, expectedType);
const receivedValue = styleValue(value, receivedType);
// check if we need to specify expected value
if (expectedTypes.length === 1 &&
isExplicable(expectedType) &&
!isBoolean(expectedType, receivedType)) {
message += ` with value ${expectedValue}`;
}
message += `, got ${receivedType} `;
// check if we need to specify received value
if (isExplicable(receivedType)) {
message += `with value ${receivedValue}.`;
}
return message;
}
function getType(ctor) {
const match = ctor && ctor.toString().match(/^\s*function (\w+)/);
return match ? match[1] : '';
}
function styleValue(value, type) {
if (type === 'String') {
return `"${value}"`;
}
else if (type === 'Number') {
return `${Number(value)}`;
}
else {
return `${value}`;
}
}
function isExplicable(type) {
const explicitTypes = ['string', 'number', 'boolean'];
return explicitTypes.some((elem) => type.toLowerCase() === elem);
}
function isBoolean(...args) {
return args.some((elem) => elem.toLowerCase() === 'boolean');
}
function tryCatch(fn) {
return function () {
try {
return fn.apply(fn, arguments);
}
catch (e) {
// TODO
console.error(e);
}
};
}
let invokeCallbackId = 1;
const invokeCallbacks = {};
function addInvokeCallback(id, name, callback, keepAlive = false) {
invokeCallbacks[id] = {
name,
keepAlive,
callback,
};
return id;
}
// onNativeEventReceive((event,data)=>{}) 需要两个参数,目前写死最多两个参数
function invokeCallback(id, res, extras) {
if (typeof id === 'number') {
const opts = invokeCallbacks[id];
if (opts) {
if (!opts.keepAlive) {
delete invokeCallbacks[id];
}
return opts.callback(res, extras);
}
}
return res;
}
function findInvokeCallbackByName(name) {
for (const key in invokeCallbacks) {
if (invokeCallbacks[key].name === name) {
return true;
}
}
return false;
}
function removeKeepAliveApiCallback(name, callback) {
for (const key in invokeCallbacks) {
const item = invokeCallbacks[key];
if (item.callback === callback && item.name === name) {
delete invokeCallbacks[key];
}
}
}
function offKeepAliveApiCallback(name) {
UniServiceJSBridge.off('api.' + name);
}
function onKeepAliveApiCallback(name) {
UniServiceJSBridge.on('api.' + name, (res) => {
for (const key in invokeCallbacks) {
const opts = invokeCallbacks[key];
if (opts.name === name) {
opts.callback(res);
}
}
});
}
function createKeepAliveApiCallback(name, callback) {
return addInvokeCallback(invokeCallbackId++, name, callback, true);
}
const API_SUCCESS = 'success';
const API_FAIL = 'fail';
const API_COMPLETE = 'complete';
function getApiCallbacks(args) {
const apiCallbacks = {};
for (const name in args) {
const fn = args[name];
if (isFunction(fn)) {
apiCallbacks[name] = tryCatch(fn);
delete args[name];
}
}
return apiCallbacks;
}
function normalizeErrMsg(errMsg, name) {
if (!errMsg || errMsg.indexOf(':fail') === -1) {
return name + ':ok';
}
return name + errMsg.substring(errMsg.indexOf(':fail'));
}
function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } = {}) {
if (!isPlainObject(args)) {
args = {};
}
const { success, fail, complete } = getApiCallbacks(args);
const hasSuccess = isFunction(success);
const hasFail = isFunction(fail);
const hasComplete = isFunction(complete);
const callbackId = invokeCallbackId++;
addInvokeCallback(callbackId, name, (res) => {
res = res || {};
res.errMsg = normalizeErrMsg(res.errMsg, name);
isFunction(beforeAll) && beforeAll(res);
if (res.errMsg === name + ':ok') {
isFunction(beforeSuccess) && beforeSuccess(res, args);
hasSuccess && success(res);
}
else {
hasFail && fail(res);
}
hasComplete && complete(res);
});
return callbackId;
}
const HOOK_SUCCESS = 'success';
const HOOK_FAIL = 'fail';
const HOOK_COMPLETE = 'complete';
const globalInterceptors = {};
const scopedInterceptors = {};
function wrapperHook(hook, params) {
return function (data) {
return hook(data, params) || data;
};
}
function queue(hooks, data, params) {
let promise = false;
for (let i = 0; i < hooks.length; i++) {
const hook = hooks[i];
if (promise) {
promise = Promise.resolve(wrapperHook(hook, params));
}
else {
const res = hook(data, params);
if (isPromise(res)) {
promise = Promise.resolve(res);
}
if (res === false) {
return {
then() { },
catch() { },
};
}
}
}
return (promise || {
then(callback) {
return callback(data);
},
catch() { },
});
}
function wrapperOptions(interceptors, options = {}) {
[HOOK_SUCCESS, HOOK_FAIL, HOOK_COMPLETE].forEach((name) => {
const hooks = interceptors[name];
if (!isArray(hooks)) {
return;
}
const oldCallback = options[name];
options[name] = function callbackInterceptor(res) {
queue(hooks, res, options).then((res) => {
return (isFunction(oldCallback) && oldCallback(res)) || res;
});
};
});
return options;
}
function wrapperReturnValue(method, returnValue) {
const returnValueHooks = [];
if (isArray(globalInterceptors.returnValue)) {
returnValueHooks.push(...globalInterceptors.returnValue);
}
const interceptor = scopedInterceptors[method];
if (interceptor && isArray(interceptor.returnValue)) {
returnValueHooks.push(...interceptor.returnValue);
}
returnValueHooks.forEach((hook) => {
returnValue = hook(returnValue) || returnValue;
});
return returnValue;
}
function getApiInterceptorHooks(method) {
const interceptor = Object.create(null);
Object.keys(globalInterceptors).forEach((hook) => {
if (hook !== 'returnValue') {
interceptor[hook] = globalInterceptors[hook].slice();
}
});
const scopedInterceptor = scopedInterceptors[method];
if (scopedInterceptor) {
Object.keys(scopedInterceptor).forEach((hook) => {
if (hook !== 'returnValue') {
interceptor[hook] = (interceptor[hook] || []).concat(scopedInterceptor[hook]);
}
});
}
return interceptor;
}
function invokeApi(method, api, options, params) {
const interceptor = getApiInterceptorHooks(method);
if (interceptor && Object.keys(interceptor).length) {
if (isArray(interceptor.invoke)) {
const res = queue(interceptor.invoke, options);
return res.then((options) => {
// 重新访问 getApiInterceptorHooks, 允许 invoke 中再次调用 addInterceptor,removeInterceptor
return api(wrapperOptions(getApiInterceptorHooks(method), options), ...params);
});
}
else {
return api(wrapperOptions(interceptor, options), ...params);
}
}
return api(options, ...params);
}
function hasCallback(args) {
if (isPlainObject(args) &&
[API_SUCCESS, API_FAIL, API_COMPLETE].find((cb) => isFunction(args[cb]))) {
return true;
}
return false;
}
function handlePromise(promise) {
// if (__UNI_FEATURE_PROMISE__) {
// return promise
// .then((data) => {
// return [null, data]
// })
// .catch((err) => [err])
// }
return promise;
}
function promisify(name, fn) {
return (args = {}, ...rest) => {
if (hasCallback(args)) {
return wrapperReturnValue(name, invokeApi(name, fn, args, rest));
}
return wrapperReturnValue(name, handlePromise(new Promise((resolve, reject) => {
invokeApi(name, fn, extend(args, { success: resolve, fail: reject }), rest);
})));
};
}
function formatApiArgs(args, options) {
const params = args[0];
if (!options ||
!options.formatArgs ||
(!isPlainObject(options.formatArgs) && isPlainObject(params))) {
return;
}
const formatArgs = options.formatArgs;
const keys = Object.keys(formatArgs);
for (let i = 0; i < keys.length; i++) {
const name = keys[i];
const formatterOrDefaultValue = formatArgs[name];
if (isFunction(formatterOrDefaultValue)) {
const errMsg = formatterOrDefaultValue(args[0][name], params);
if (isString(errMsg)) {
return errMsg;
}
}
else {
// defaultValue
if (!hasOwn(params, name)) {
params[name] = formatterOrDefaultValue;
}
}
}
}
function invokeSuccess(id, name, res) {
const result = {
errMsg: name + ':ok',
};
{
result.errSubject = name;
}
return invokeCallback(id, extend((res || {}), result));
}
function invokeFail(id, name, errMsg, errRes = {}) {
const errMsgPrefix = name + ':fail';
let apiErrMsg = '';
if (!errMsg) {
apiErrMsg = errMsgPrefix;
}
else if (errMsg.indexOf(errMsgPrefix) === 0) {
apiErrMsg = errMsg;
}
else {
apiErrMsg = errMsgPrefix + ' ' + errMsg;
}
let res = extend({ errMsg: apiErrMsg }, errRes);
{
if (typeof UniError !== 'undefined') {
res =
typeof errRes.errCode !== 'undefined'
? new UniError(name, errRes.errCode, apiErrMsg)
: new UniError(apiErrMsg, errRes);
}
}
return invokeCallback(id, res);
}
function beforeInvokeApi(name, args, protocol, options) {
if ((process.env.NODE_ENV !== 'production')) {
validateProtocols(name, args, protocol);
}
if (options && options.beforeInvoke) {
const errMsg = options.beforeInvoke(args);
if (isString(errMsg)) {
return errMsg;
}
}
const errMsg = formatApiArgs(args, options);
if (errMsg) {
return errMsg;
}
}
function checkCallback(callback) {
if (!isFunction(callback)) {
throw new Error('Invalid args: type check failed for args "callback". Expected Function');
}
}
function wrapperOnApi(name, fn, options) {
return (callback) => {
checkCallback(callback);
const errMsg = beforeInvokeApi(name, [callback], undefined, options);
if (errMsg) {
throw new Error(errMsg);
}
// 是否是首次调用on,如果是首次,需要初始化onMethod监听
const isFirstInvokeOnApi = !findInvokeCallbackByName(name);
createKeepAliveApiCallback(name, callback);
if (isFirstInvokeOnApi) {
onKeepAliveApiCallback(name);
fn();
}
};
}
function wrapperOffApi(name, fn, options) {
return (callback) => {
checkCallback(callback);
const errMsg = beforeInvokeApi(name, [callback], undefined, options);
if (errMsg) {
throw new Error(errMsg);
}
name = name.replace('off', 'on');
removeKeepAliveApiCallback(name, callback);
// 是否还存在监听,若已不存在,则移除onMethod监听
const hasInvokeOnApi = findInvokeCallbackByName(name);
if (!hasInvokeOnApi) {
offKeepAliveApiCallback(name);
fn();
}
};
}
function parseErrMsg(errMsg) {
if (!errMsg || isString(errMsg)) {
return errMsg;
}
if (errMsg.stack) {
return errMsg.message;
}
return errMsg;
}
function wrapperTaskApi(name, fn, protocol, options) {
return (args) => {
const id = createAsyncApiCallback(name, args, options);
const errMsg = beforeInvokeApi(name, [args], protocol, options);
if (errMsg) {
return invokeFail(id, name, errMsg);
}
return fn(args, {
resolve: (res) => invokeSuccess(id, name, res),
reject: (errMsg, errRes) => invokeFail(id, name, parseErrMsg(errMsg), errRes),
});
};
}
function wrapperSyncApi(name, fn, protocol, options) {
return (...args) => {
const errMsg = beforeInvokeApi(name, args, protocol, options);
if (errMsg) {
throw new Error(errMsg);
}
return fn.apply(null, args);
};
}
function wrapperAsyncApi(name, fn, protocol, options) {
return wrapperTaskApi(name, fn, protocol, options);
}
function defineOnApi(name, fn, options) {
return wrapperOnApi(name, fn, options);
}
function defineOffApi(name, fn, options) {
return wrapperOffApi(name, fn, options);
}
function defineTaskApi(name, fn, protocol, options) {
return promisify(name, wrapperTaskApi(name, fn, (process.env.NODE_ENV !== 'production') ? protocol : undefined, options));
}
function defineSyncApi(name, fn, protocol, options) {
return wrapperSyncApi(name, fn, (process.env.NODE_ENV !== 'production') ? protocol : undefined, options);
}
function defineAsyncApi(name, fn, protocol, options) {
return promisify(name, wrapperAsyncApi(name, fn, (process.env.NODE_ENV !== 'production') ? protocol : undefined, options));
}
const API_ADD_INTERCEPTOR = 'addInterceptor';
const API_REMOVE_INTERCEPTOR = 'removeInterceptor';
const AddInterceptorProtocol = [
{
name: 'method',
type: [String, Object],
required: true,
},
];
const RemoveInterceptorProtocol = AddInterceptorProtocol;
function mergeInterceptorHook(interceptors, interceptor) {
Object.keys(interceptor).forEach((hook) => {
if (isFunction(interceptor[hook])) {
interceptors[hook] = mergeHook(interceptors[hook], interceptor[hook]);
}
});
}
function removeInterceptorHook(interceptors, interceptor) {
if (!interceptors || !interceptor) {
return;
}
Object.keys(interceptor).forEach((name) => {
const hooks = interceptors[name];
const hook = interceptor[name];
if (isArray(hooks) && isFunction(hook)) {
remove(hooks, hook);
}
});
}
function mergeHook(parentVal, childVal) {
const res = childVal
? parentVal
? parentVal.concat(childVal)
: isArray(childVal)
? childVal
: [childVal]
: parentVal;
return res ? dedupeHooks(res) : res;
}
function dedupeHooks(hooks) {
const res = [];
for (let i = 0; i < hooks.length; i++) {
if (res.indexOf(hooks[i]) === -1) {
res.push(hooks[i]);
}
}
return res;
}
const addInterceptor = defineSyncApi(API_ADD_INTERCEPTOR, (method, interceptor) => {
if (isString(method) && isPlainObject(interceptor)) {
mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), interceptor);
}
else if (isPlainObject(method)) {
mergeInterceptorHook(globalInterceptors, method);
}
}, AddInterceptorProtocol);
const removeInterceptor = defineSyncApi(API_REMOVE_INTERCEPTOR, (method, interceptor) => {
if (isString(method)) {
if (isPlainObject(interceptor)) {
removeInterceptorHook(scopedInterceptors[method], interceptor);
}
else {
delete scopedInterceptors[method];
}
}
else if (isPlainObject(method)) {
removeInterceptorHook(globalInterceptors, method);
}
}, RemoveInterceptorProtocol);
export { addInterceptor, defineAsyncApi, defineOffApi, defineOnApi, defineSyncApi, defineTaskApi, removeInterceptor };
+341
View File
@@ -0,0 +1,341 @@
'use strict';
var appVite = require('@dcloudio/uni-app-vite');
var path = require('path');
var fs = require('fs-extra');
var uniCliShared = require('@dcloudio/uni-cli-shared');
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
var appVite__default = /*#__PURE__*/_interopDefault(appVite);
var path__default = /*#__PURE__*/_interopDefault(path);
var fs__default = /*#__PURE__*/_interopDefault(fs);
var StandaloneExtApis = [
{
type: "extapi",
plugin: "uni-facialRecognitionVerify",
apis: [
"startFacialRecognitionVerify",
"getFacialRecognitionMetaInfo"
],
version: "1.0.2"
},
{
type: "provider",
plugin: "uni-oauth-huawei",
provider: "huawei",
service: "oauth",
version: "1.0.1"
},
{
type: "provider",
plugin: "uni-payment-alipay",
provider: "alipay",
service: "payment",
version: "1.0.1"
},
{
type: "extapi",
plugin: "uni-push",
apis: [
"getPushClientId",
"onPushMessage",
"offPushMessage",
"createPushMessage",
"setAppBadgeNumber"
],
version: "1.0.1"
}
];
const commondGlobals = {
vue: 'Vue',
'@vue/shared': 'uni.VueShared',
};
const harmonyGlobals = [
/^@ohos\./,
/^@kit\./,
/^@hms\./,
/^@arkts\./,
/^@system\./,
'@ohos/hypium',
'@ohos/hamock',
];
function isHarmoneyGlobal(id) {
return harmonyGlobals.some((harmonyGlobal) => typeof harmonyGlobal === 'string'
? harmonyGlobal === id
: harmonyGlobal.test(id));
}
function generateHarmonyImportSpecifier(id) {
return id.replace(/([@\/\.])/g, function (_, $1) {
switch ($1) {
case '.':
return '_';
case '/':
return '__';
default:
return '';
}
});
}
function generateHarmonyImportExternalCode(hamonyPackageNames) {
return hamonyPackageNames
.filter((hamonyPackageName) => isHarmoneyGlobal(hamonyPackageName))
.map((hamonyPackageName) => `import ${generateHarmonyImportSpecifier(hamonyPackageName)} from '${hamonyPackageName}';`)
.join('');
}
function uniAppHarmonyPlugin() {
return {
name: 'uni:app-harmony',
apply: 'build',
config() {
return {
build: {
rollupOptions: {
external: [...Object.keys(commondGlobals), ...harmonyGlobals],
output: {
globals: function (id) {
return (commondGlobals[id] ||
(isHarmoneyGlobal(id)
? generateHarmonyImportSpecifier(id)
: ''));
},
},
},
},
};
},
async generateBundle(_, bundle) {
genAppHarmonyUniModules(process.env.UNI_INPUT_DIR, uniCliShared.getCurrentCompiledUTSPlugins());
for (const key in bundle) {
const serviceBundle = bundle[key];
if (serviceBundle.code) {
serviceBundle.code =
generateHarmonyImportExternalCode(serviceBundle.imports) +
serviceBundle.code;
}
}
},
async writeBundle() {
if (!uniCliShared.isNormalCompileTarget()) {
return;
}
// x 上暂时编译所有uni ext api,不管代码里是否调用了
await uniCliShared.buildUniExtApis();
},
};
}
// 仅存放重命名的provider service
const SupportedProviderService = {
'uni-oauth': {
huawei: 'huawei',
},
'uni-payment': {
weixin: 'wxpay',
},
};
/**
* 获取manifest.json中勾选的provider
*/
function getRelatedProviders(inputDir) {
const manifest = uniCliShared.parseManifestJsonOnce(inputDir);
const providers = [];
const manifestModules = manifest?.['app-harmony']?.distribute?.modules;
if (!manifestModules) {
return providers;
}
for (const uniModule in manifestModules) {
if (Object.prototype.hasOwnProperty.call(manifestModules, uniModule)) {
const ProviderNameMap = SupportedProviderService[uniModule];
if (!ProviderNameMap) {
continue;
}
const relatedProviders = manifestModules[uniModule];
for (const name in relatedProviders) {
if (Object.prototype.hasOwnProperty.call(relatedProviders, name)) {
const providerConf = relatedProviders[name];
if (!providerConf) {
continue;
}
if (!providerConf.__platform__ ||
(Array.isArray(providerConf.__platform__) &&
providerConf.__platform__.includes('harmonyos'))) {
const providerName = ProviderNameMap[name];
providers.push({
service: uniModule.replace(/^uni-/, ''),
name: providerName || name,
});
}
}
}
}
}
return providers;
}
const SupportedModules = {
'uni-facialRecognitionVerify': 'uni-facialRecognitionVerify',
'uni-push': 'uni-push',
};
// 获取uni_modules中的相关模块
function getRelatedModules(inputDir) {
const manifest = uniCliShared.parseManifestJsonOnce(inputDir);
const modules = [];
const manifestModules = manifest?.['app-harmony']?.distribute?.modules;
if (!manifestModules) {
return modules;
}
for (const manifestModule in manifestModules) {
if (Object.prototype.hasOwnProperty.call(manifestModules, manifestModule)) {
const moduleName = SupportedModules[manifestModule];
if (!moduleName) {
continue;
}
modules.push(moduleName);
}
}
return modules;
}
function genAppHarmonyUniModules(inputDir, utsPlugins) {
const uniModulesDir = path__default.default.resolve(inputDir, 'uni_modules');
const importCodes = [];
const extApiCodes = [];
const registerCodes = [];
const projectDeps = [];
utsPlugins.forEach((plugin) => {
const injects = uniCliShared.parseUniExtApi(path__default.default.resolve(uniModulesDir, plugin), plugin, true, 'app-harmony', 'arkts');
const hamonyPackageName = `@uni_modules/${plugin.toLowerCase()}`;
if (injects) {
Object.keys(injects).forEach((key) => {
const inject = injects[key];
if (Array.isArray(inject) && inject.length > 1) {
const apiName = inject[1];
importCodes.push(`import { ${inject[1]} } from '${hamonyPackageName}'`);
extApiCodes.push(`uni.${apiName} = ${apiName}`);
}
});
}
else {
const ident = uniCliShared.camelize(plugin);
importCodes.push(`import * as ${ident} from '${hamonyPackageName}'`);
registerCodes.push(`uni.registerUTSPlugin('uni_modules/${plugin}', ${ident})`);
}
projectDeps.push({
moduleSpecifier: hamonyPackageName,
plugin,
source: 'local',
});
});
const relatedProviders = getRelatedProviders(inputDir);
const relatedModules = getRelatedModules(inputDir);
relatedModules.forEach((module) => {
const harmonyModuleName = `@uni_modules/${module.toLowerCase()}`;
if (utsPlugins.has(module)) ;
else {
const matchedStandaloneExtApi = StandaloneExtApis.find((item) => item.plugin === module);
if (matchedStandaloneExtApi) {
projectDeps.push({
moduleSpecifier: harmonyModuleName,
plugin: module,
source: 'ohpm',
version: '*',
});
matchedStandaloneExtApi.apis?.forEach((apiName) => {
importCodes.push(`import { ${apiName} } from '${harmonyModuleName}'`);
extApiCodes.push(`uni.${apiName} = ${apiName}`);
});
}
}
});
const importProviderCodes = [];
const registerProviderCodes = [];
const providers = uniCliShared.getUniExtApiProviderRegisters();
const allProviders = providers.map((provider) => {
return {
service: provider.service,
name: provider.name,
moduleSpecifier: `@uni_modules/${provider.plugin.toLowerCase()}`,
plugin: provider.plugin,
source: 'local',
version: undefined,
};
});
StandaloneExtApis.filter((item) => {
return item.type === 'provider';
}).forEach((extapi) => {
if (allProviders.find((item) => item.plugin === extapi.plugin)) {
return;
}
const [_, service, provider] = extapi.plugin.split('-');
allProviders.push({
service,
name: provider,
moduleSpecifier: `@uni_modules/${extapi.plugin.toLowerCase()}`,
plugin: extapi.plugin,
source: 'ohpm',
version: '*',
});
});
relatedProviders.forEach((relatedProvider) => {
const provider = allProviders.find((item) => item.service === relatedProvider.service &&
item.name === relatedProvider.name);
if (!provider) {
return;
}
projectDeps.push({
moduleSpecifier: provider.moduleSpecifier,
plugin: provider.plugin,
source: provider.source,
version: provider.version,
});
const className = uniCliShared.formatExtApiProviderName(provider.service, provider.name);
importProviderCodes.push(`import { ${className} } from '${provider.moduleSpecifier}'`);
registerProviderCodes.push(`registerUniProvider('${provider.service}', '${provider.name}', new ${className}())`);
});
if (importProviderCodes.length) {
importCodes.push(...importProviderCodes);
extApiCodes.push(...registerProviderCodes);
}
importCodes.unshift(`import { registerUniProvider, uni } from '@dcloudio/uni-app-runtime'`);
const uniModuleEntryDir = uniCliShared.resolveUTSCompiler().resolveAppHarmonyUniModulesEntryDir();
fs__default.default.outputFileSync(path__default.default.resolve(uniModuleEntryDir, 'index.generated.ets'), `// This file is automatically generated by uni-app.
// Do not modify this file -- YOUR CHANGES WILL BE ERASED!
${importCodes.join('\n')}
export function initUniModules() {
initUniExtApi()
${registerCodes.join('\n ')}
}
function initUniExtApi() {
${extApiCodes.join('\n ')}
}
`);
const dependencies = {};
const modules = [];
projectDeps.forEach((dep) => {
if (dep.source === 'local') {
const depPath = './uni_modules/' + dep.plugin;
dependencies[dep.moduleSpecifier] = depPath;
modules.push({
name: dep.moduleSpecifier
.replace(/@/g, '')
.replace(/\//g, '__')
.replace(/-/g, '_'),
srcPath: depPath,
});
}
else {
if (!dependencies[dep.moduleSpecifier]) {
dependencies[dep.moduleSpecifier] = dep.version;
}
}
});
// TODO 写入到用户项目的oh-package.json5、build-profile.json5内
fs__default.default.outputJSONSync(path__default.default.resolve(uniModuleEntryDir, 'oh-package.json5'), { dependencies }, { spaces: 2 });
fs__default.default.outputJSONSync(path__default.default.resolve(uniModuleEntryDir, 'build-profile.json5'), { modules }, { spaces: 2 });
}
var index = [appVite__default.default, uniAppHarmonyPlugin];
module.exports = index;
File diff suppressed because it is too large Load Diff
+1
View File
@@ -0,0 +1 @@
[https://dcloud.io/license/uni-app.html](https://dcloud.io/license/uni-app.html)
+50
View File
@@ -0,0 +1,50 @@
{
"name": "@dcloudio/uni-app-harmony",
"version": "3.0.0-4030620241128001",
"description": "@dcloudio/uni-app-harmony",
"files": [
"dist"
],
"sideEffects": [
"lib/automator.js"
],
"repository": {
"type": "git",
"url": "git+https://github.com/dcloudio/uni-app.git",
"directory": "packages/uni-app-harmony"
},
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/dcloudio/uni-app/issues"
},
"gitHead": "33e807d66e1fe47e2ee08ad9c59247e37b8884da",
"uni-app": {
"name": "uni-app-harmony",
"apply": [
"app-harmony"
],
"main": "dist/uni.compiler.js"
},
"dependencies": {
"@dcloudio/uni-app-vite": "3.0.0-4030620241128001",
"debug": "^4.3.3",
"fs-extra": "^10.0.0",
"licia": "^1.29.0",
"postcss-selector-parser": "^6.0.6"
},
"devDependencies": {
"@dcloudio/uni-cli-shared": "3.0.0-4030620241128001",
"@dcloudio/uni-app-plus": "3.0.0-4030620241128001",
"@dcloudio/uni-components": "3.0.0-4030620241128001",
"@dcloudio/uni-i18n": "3.0.0-4030620241128001",
"@dcloudio/uni-shared": "3.0.0-4030620241128001",
"@types/pako": "1.0.2",
"@types/google.maps": "^3.45.6",
"@amap/amap-jsapi-types": "^0.0.8",
"@vue/compiler-sfc": "3.4.21",
"autoprefixer": "^10.4.18",
"pako": "^1.0.11",
"postcss": "^8.4.21",
"vue": "3.4.21"
}
}