• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16var __decorate = (this && this.__decorate) || function (a12, b12, c12, d12) {
17    var e12 = arguments.length,
18        f12 = e12 < 3 ? b12 : d12 === null ? d12 = Object.getOwnPropertyDescriptor(b12, c12) : d12, g12;
19    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
20        f12 = Reflect.decorate(a12, b12, c12, d12);
21    } else {
22        for (var h12 = a12.length - 1; h12 >= 0; h12--) {
23            if (g12 = a12[h12]) {
24                f12 = (e12 < 3 ? g12(f12) : e12 > 3 ? g12(b12, c12, f12) : g12(b12, c12)) || f12;
25            }
26        }
27    }
28    return e12 > 3 && f12 && Object.defineProperty(b12, c12, f12), f12;
29};
30
31if (!("finalizeConstruction" in ViewPU.prototype)) {
32    Reflect.set(ViewPU.prototype, "finalizeConstruction", () => {
33    });
34}
35const webView = requireNapi('web.webview');
36const router = requireNapi('router');
37const deviceInfo = requireNapi('deviceInfo');
38const geoLocationManager = requireNapi('geoLocationManager');
39const bundleManager = requireNapi('bundle.bundleManager');
40const abilityAccessCtrl = requireNapi('abilityAccessCtrl');
41const connection = requireNapi('net.connection');
42const request = requireNapi('request');
43const fs = requireNapi('file.fs');
44const util = requireNapi('util');
45const photoAccessHelper = requireNapi('file.photoAccessHelper');
46const filePreview = globalThis.requireNapi('filemanagement.filepreview', false, '', 'hms');
47const fileUri = requireNapi('file.fileuri');
48const picker = requireNapi('multimedia.cameraPicker');
49const filePicker = requireNapi('file.picker');
50const call = requireNapi('telephony.call');
51const authentication = globalThis.requireNapi('core.authentication', false, '', 'hms');
52const paymentService = globalThis.requireNapi('core.payment.paymentService', false, '', 'hms');
53const atomicServiceWebNapi = requireInternal('atomicservice.AtomicServiceWeb');
54const hiAppEvent = globalThis.requireNapi('hiviewdfx.hiAppEvent');
55
56let atomicBasicEngine = null;
57
58function loadAtomicBasicEngine() {
59    try {
60        import('@hms:atomicservicedistribution.atomicbasicengine').then((z10) => {
61            console.log('AtomicServiceWeb loadAtomicBasicEngine success');
62            atomicBasicEngine = z10;
63        }).catch((y10) => {
64            console.error('AtomicServiceWeb loadAtomicBasicEngine error, message: ' + y10.message);
65        });
66    } catch (x10) {
67        console.error('AtomicServiceWeb loadAtomicBasicEngine error, message: ' + x10.message);
68    }
69}
70
71loadAtomicBasicEngine();
72
73class AsError {
74    constructor(m11, n11) {
75        this.code = m11;
76        this.message = n11;
77    }
78}
79
80class JsApiConfig {
81    constructor(i11, j11, k11, l11) {
82        this.apiName = i11;
83        this.minVersion = j11;
84        this.maxVersion = k11;
85        this.requiredFieldNames = l11;
86    }
87}
88
89const LOG_ENABLE = true;
90const LOG_PREFIX = '[AtomicServiceWebLog]';
91const UPLOAD_IMAGE_CACHE_DIR = '/cache/';
92const JAVA_SCRIPT_PROXY_OBJECT_NAME = 'atomicServiceProxy';
93const JAVA_SCRIPT_PROXY_API_NAME_LIST = ['invokeJsApi'];
94const ATOMIC_SERVICE_JS_API_MAP = new Map();
95const registerJsApi = (u11, v11, w11, x11, y11) => {
96    ATOMIC_SERVICE_JS_API_MAP.set(u11, new JsApiConfig(v11, w11, x11, y11));
97};
98const MAX_VERSION = '99.99.99';
99const ATOMIC_SERVICE_JS_SDK_CURRENT_VERSION = '1.0.1';
100const PERMISSION_APPROXIMATELY_LOCATION = 'ohos.permission.APPROXIMATELY_LOCATION';
101const TEL_PROTOCOL = 'tel:';
102const MAILTO_PROTOCOL = 'mailto:';
103const WANT_ACTION_SEND_TO_DATA = 'ohos.want.action.sendToData';
104const RESOURCE_RAWFILE = 'resource://rawfile';
105const TYPE_AS_WEB = 'ASWeb';
106const WEB_PERMISSIONS = {
107    'TYPE_VIDEO_CAPTURE': 'ohos.permission.CAMERA',
108    'TYPE_AUDIO_CAPTURE': 'ohos.permission.MICROPHONE'
109};
110const SYSTEM_INTERNAL_ERROR = new AsError(500, 'System internal error.');
111const JS_API_INVALID_INVOKE_ERROR = new AsError(200001, 'Invalid invoke.');
112const PARAM_REQUIRED_ERROR_CODE = 200002;
113const PARAM_NUMBER_POSITIVE_ERROR_CODE = 200003;
114const ROUTER_PARAM_MODE_INVALID_ERROR = new AsError(200004, 'Param mode is invalid.');
115const BACK_URL_NOT_EXIST_OR_OPENED_ERROR = new AsError(200005, 'Url is not exist or opened, can not be back.');
116const NAV_PATH_STACK_NOT_EXIST_ERROR_CODE = 200006;
117const POP_PATH_NAME_NOT_EXIST_ERROR = new AsError(200007, 'Name is not exist or opened, can not be pop.');
118const POP_PATH_PARAM_INDEX_INVALID_ERROR = new AsError(200008, 'Param index is invalid.');
119const POP_PATH_INDEX_OUT_OF_RANGE_ERROR = new AsError(200009, 'The Index is out of range.');
120const UPLOAD_IMAGE_FILES_REQUIRED_ERROR = new AsError(200010, 'Param files is required.');
121const UPLOAD_IMAGE_FILE_NOT_EXIST_ERROR_CODE = 200011;
122const UPLOAD_IMAGE_FILES_URI_REQUIRED_ERROR = new AsError(200012, 'Param uri of files is required.');
123const UPLOAD_FILE_ERROR = new AsError(200013, 'Upload file error.');
124const IMAGE_CAN_NOT_PREVIEW_ERROR = new AsError(200014, 'The filePath can not preview.');
125const NETWORK_NO_ACTIVE_ERROR = new AsError(200015, 'The network is not active.');
126const PERMISSION_LOCATION_USER_REFUSED_ERROR = 200016;
127const LOGIN_STATE_INVALID_ERROR = new AsError(200017, 'Login state is invalid.');
128const LOGIN_RESPONSE_DATA_NULL_ERROR = new AsError(200018, 'Response data is null.');
129const REQUEST_PAYMENT_ORDER_STR_INVALID_ERROR = new AsError(200019, 'orderStr is not type string.');
130const NEED_REPORTED_API_LIST = ['has.cameraPicker.pick', 'has.photoViewPicker.select', 'has.filePreview.openPreview', 'has.request.uploadFile', 'has.request.downloadFile',
131    'has.connection.getNetworkType', 'has.location.getLocation', 'has.account.login', 'has.payment.requestPayment'];
132registerJsApi('router.pushUrl', 'pushUrl', '1.0.0', MAX_VERSION, ['url']);
133registerJsApi('router.replaceUrl', 'replaceUrl', '1.0.0', MAX_VERSION, ['url']);
134registerJsApi('router.back', 'backUrl', '1.0.0', MAX_VERSION, []);
135registerJsApi('router.clear', 'clearUrl', '1.0.0', MAX_VERSION, []);
136registerJsApi('navPathStack.pushPath', 'pushPath', '1.0.0', MAX_VERSION, ['name']);
137registerJsApi('navPathStack.replacePath', 'replacePath', '1.0.0', MAX_VERSION, ['name']);
138registerJsApi('navPathStack.pop', 'popPath', '1.0.0', MAX_VERSION, []);
139registerJsApi('navPathStack.clear', 'clearPath', '1.0.0', MAX_VERSION, []);
140registerJsApi('asWeb.postMessage', 'postMessage', '1.0.0', MAX_VERSION, ['data']);
141registerJsApi('asWeb.getEnv', 'getEnv', '1.0.0', MAX_VERSION, []);
142registerJsApi('asWeb.checkJsApi', 'checkJsApi', '1.0.0', MAX_VERSION, ['jsApiList']);
143registerJsApi('cameraPicker.pick', 'pickCamera', '1.0.0', MAX_VERSION, ['mediaTypes', 'cameraPosition']);
144registerJsApi('photoViewPicker.select', 'selectPhoto', '1.0.0', MAX_VERSION, []);
145registerJsApi('filePreview.openPreview', 'openPreview', '1.0.0', MAX_VERSION, ['uri']);
146registerJsApi('request.uploadFile', 'uploadFile', '1.0.0', MAX_VERSION, ['url', 'files']);
147registerJsApi('request.downloadFile', 'downloadFile', '1.0.0', MAX_VERSION, ['url']);
148registerJsApi('connection.getNetworkType', 'getNetworkType', '1.0.0', MAX_VERSION, []);
149registerJsApi('location.getLocation', 'getLocation', '1.0.0', MAX_VERSION, []);
150registerJsApi('account.login', 'login', '1.0.1', MAX_VERSION, []);
151registerJsApi('payment.requestPayment', 'requestPayment', '1.0.1', MAX_VERSION, ['orderStr']);
152
153export class AtomicServiceWeb extends ViewPU {
154    constructor(s10, t10, u10, v10 = -1, w10 = undefined, x10) {
155        super(s10, u10, v10, x10);
156        if (typeof w10 === "function") {
157            this.paramsGenerator_ = w10;
158        }
159        this.src = undefined;
160        this.navPathStack = undefined;
161        this.__mixedMode = new SynchedPropertySimpleOneWayPU(t10.mixedMode, this, "mixedMode");
162        this.__darkMode = new SynchedPropertySimpleOneWayPU(t10.darkMode, this, "darkMode");
163        this.__forceDarkAccess = new SynchedPropertySimpleOneWayPU(t10.forceDarkAccess, this, "forceDarkAccess");
164        this.__nestedScroll = new SynchedPropertyObjectOneWayPU(t10.nestedScroll, this, 'nestedScroll');
165        this.__controller = new SynchedPropertyNesedObjectPU(t10.controller, this, "controller");
166        this.onMessage = () => {
167        };
168        this.onErrorReceive = () => {
169        };
170        this.onHttpErrorReceive = () => {
171        };
172        this.onPageBegin = () => {
173        };
174        this.onPageEnd = () => {
175        };
176        this.onProgressChange = () => {
177        };
178        this.onControllerAttached = undefined;
179        this.onLoadIntercept = undefined;
180        this.context = this.getUIContext().getHostContext();
181        this.webViewController = new webView.WebviewController();
182        this.schemeHandler = new webView.WebSchemeHandler();
183        this.atomicService = undefined;
184        this.atomicServiceProxy = undefined;
185        this.setInitiallyProvidedValue(t10);
186        this.finalizeConstruction();
187    }
188
189    setInitiallyProvidedValue(r10) {
190        if (r10.src !== undefined) {
191            this.src = r10.src;
192        }
193        if (r10.navPathStack !== undefined) {
194            this.navPathStack = r10.navPathStack;
195        }
196        this.__controller.set(r10.controller);
197        if (r10.onMessage !== undefined) {
198            this.onMessage = r10.onMessage;
199        }
200        if (r10.onErrorReceive !== undefined) {
201            this.onErrorReceive = r10.onErrorReceive;
202        }
203        if (r10.onHttpErrorReceive !== undefined) {
204            this.onHttpErrorReceive = r10.onHttpErrorReceive;
205        }
206        if (r10.onPageBegin !== undefined) {
207            this.onPageBegin = r10.onPageBegin;
208        }
209        if (r10.onPageEnd !== undefined) {
210            this.onPageEnd = r10.onPageEnd;
211        }
212        if (r10.onProgressChange !== undefined) {
213            this.onProgressChange = r10.onProgressChange;
214        }
215        if (r10.onControllerAttached !== undefined) {
216            this.onControllerAttached = r10.onControllerAttached;
217        }
218        if (r10.onLoadIntercept !== undefined) {
219            this.onLoadIntercept = r10.onLoadIntercept;
220        }
221        if (r10.context !== undefined) {
222            this.context = r10.context;
223        }
224        if (r10.webViewController !== undefined) {
225            this.webViewController = r10.webViewController;
226        }
227        if (r10.schemeHandler !== undefined) {
228            this.schemeHandler = r10.schemeHandler;
229        }
230        if (r10.atomicService !== undefined) {
231            this.atomicService = r10.atomicService;
232        }
233        if (r10.atomicServiceProxy !== undefined) {
234            this.atomicServiceProxy = r10.atomicServiceProxy;
235        }
236    }
237
238    updateStateVars(q10) {
239        this.__mixedMode.reset(q10.mixedMode);
240        this.__darkMode.reset(q10.darkMode);
241        this.__forceDarkAccess.reset(q10.forceDarkAccess);
242        this.__nestedScroll.reset(q10.nestedScroll);
243        this.__controller.set(q10.controller);
244    }
245
246    purgeVariableDependenciesOnElmtId(p10) {
247        this.__mixedMode.purgeDependencyOnElmtId(p10);
248        this.__darkMode.purgeDependencyOnElmtId(p10);
249        this.__forceDarkAccess.purgeDependencyOnElmtId(p10);
250        this.__nestedScroll.purgeDependencyOnElmtId(p10);
251        this.__controller.purgeDependencyOnElmtId(p10);
252    }
253
254    aboutToBeDeleted() {
255        this.__mixedMode.aboutToBeDeleted();
256        this.__darkMode.aboutToBeDeleted();
257        this.__forceDarkAccess.aboutToBeDeleted();
258        this.__nestedScroll.aboutToBeDeleted();
259        this.__controller.aboutToBeDeleted();
260        SubscriberManager.Get().delete(this.id__());
261        this.aboutToBeDeletedInternal();
262    }
263
264    get mixedMode() {
265        return this.__mixedMode.get();
266    }
267
268    set mixedMode(t11) {
269        this.__mixedMode.set(t11);
270    }
271
272    get darkMode() {
273        return this.__darkMode.get();
274    }
275
276    set darkMode(s11) {
277        this.__darkMode.set(s11);
278    }
279
280    get forceDarkAccess() {
281        return this.__forceDarkAccess.get();
282    }
283
284    set forceDarkAccess(r11) {
285        this.__forceDarkAccess.set(r11);
286    }
287
288    get nestedScroll() {
289        return this.__nestedScroll.get();
290    }
291
292    set nestedScroll(d9) {
293        this.__nestedScroll.set(d9);
294    }
295
296    get controller() {
297        return this.__controller.get();
298    }
299
300    aboutToAppear() {
301        if (!this.atomicService) {
302            this.atomicService = new AtomicServiceApi(this.context, this.navPathStack, this.onMessage);
303            this.atomicServiceProxy = new AtomicServiceProxy(this.atomicService);
304        }
305        try {
306            let h2 = bundleManager.getBundleInfoForSelfSync(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
307            if (h2?.appInfo?.appProvisionType === 'debug') {
308                console.log(`AtomicServiceWeb setWebDebuggingAccess`);
309                webView.WebviewController.setWebDebuggingAccess(true);
310            }
311        } catch (d2) {
312            console.error(`AtomicServiceWeb set Web Debug Mode failed, code is ${d2.code}, message is ${d2.message}`);
313        }
314        this.initDomainCheckLog();
315        HiAnalyticsUtil.reportComponentEvent();
316    }
317
318    aboutToDisappear() {
319        this.atomicService?.notifyMessage();
320    }
321
322    initialRender() {
323        this.observeComponentCreation2((g10, h10) => {
324            Web.create({ src: this.src, controller: this.webViewController });
325            Web.zoomAccess(false);
326            Web.allowWindowOpenMethod(false);
327            Web.domStorageAccess(true);
328            Web.layoutMode(WebLayoutMode.NONE);
329            Web.mixedMode(this.mixedMode);
330            Web.darkMode(this.darkMode);
331            Web.forceDarkAccess(this.forceDarkAccess);
332            Web.nestedScroll(ObservedObject.GetRawObject(this.nestedScroll));
333            Web.onErrorReceive((q11) => this.onCommonCallBack('onErrorReceive', q11, this.onErrorReceive));
334            Web.onHttpErrorReceive((p11) => this.onCommonCallBack('onHttpErrorReceive', p11, this.onHttpErrorReceive));
335            Web.onPageBegin((l10) => this.onCommonCallBack('onPageBegin', l10, this.onPageBegin));
336            Web.onPageEnd((b11) => this.onCommonCallBack('onPageEnd', b11, this.onPageEnd));
337            Web.onProgressChange((a11) => this.onCommonCallBack('onProgressChange', a11, this.onProgressChange));
338            Web.onControllerAttached(() => {
339                this.registerJavaScriptProxy();
340                this.schemeHandler.onRequestStart((z10) => {
341                    return !this.interceptUrl(z10.getRequestUrl(), z10.isMainFrame(), z10.getRequestResourceType());
342                });
343                this.webViewController.setWebSchemeHandler('http', this.schemeHandler);
344                this.webViewController.setWebSchemeHandler('https', this.schemeHandler);
345                this.initAtomicServiceWebController();
346                if (this.onControllerAttached) {
347                    try {
348                        this.onControllerAttached();
349                    } catch (y10) {
350                        console.error(`AtomicServiceWeb onControllerAttached failed, code is ${y10.code}, message is ${y10.message}`);
351                    }
352                }
353            });
354            Web.onOverrideUrlLoading((i10) => {
355                return !this.interceptOverrideUrlLoading(i10.getRequestUrl());
356            });
357            Web.onLoadIntercept(m7 => {
358                let n7 = !this.checkUrl(m7.data.getRequestUrl());
359                if (!n7 && this.onLoadIntercept) {
360                    try {
361                        return this.onLoadIntercept(m7);
362                    } catch (u7) {
363                        console.error(`AtomicServiceWeb onLoadIntercept failed, code is ${u7.code}, message is ${u7.message}`);
364                        return true;
365                    }
366                }
367                return n7;
368            });
369            Web.onPermissionRequest((c10) => { this.handleOnPermissionRequest(c10); });
370        }, Web);
371    }
372
373    onCommonCallBack(q5, e6, j6) {
374        try {
375            j6 && j6(e6);
376        } catch (k7) {
377            console.error(`AtomicServiceWeb ${q5} failed, code is ${k7.code}, message is ${k7.message}`);
378        }
379    }
380
381    registerJavaScriptProxy() {
382        try {
383            this.webViewController.registerJavaScriptProxy(this.atomicServiceProxy, JAVA_SCRIPT_PROXY_OBJECT_NAME,
384                JAVA_SCRIPT_PROXY_API_NAME_LIST);
385        } catch (d10) {
386            let e10 = d10;
387            console.error(`AtomicServiceWeb registerJavaScriptProxy failed, code is ${e10.code}, message is ${e10.message}`);
388        }
389    }
390
391    initAtomicServiceWebController() {
392        if (!this.controller) {
393            return;
394        }
395        this.controller.setWebviewController(this.webViewController);
396    }
397
398    cutUrl(b10) {
399        if (b10) {
400            let c10 = b10.indexOf('?');
401            if (c10 > -1) {
402                return b10.substring(0, c10);
403            }
404        }
405        return b10;
406    }
407
408    checkUrl(q1) {
409        if (!q1) {
410            return false;
411        }
412        if (q1.startsWith('resource://rawfile')) {
413            return true;
414        }
415        try {
416            let w1 = this.context.abilityInfo.bundleName;
417            let t1 = 'webView';
418            q1 = this.cutUrl(q1);
419            let res = atomicServiceWebNapi.checkUrl(w1, t1, q1);
420            console.debug(`AtomicServiceWeb checkUrl ret=${res === 0} url=${q1}`);
421            return res === 0;
422        } catch (j2) {
423            let n2 = j2;
424            console.error(`AtomicServiceWeb checkUrl failed, code is ${n2.code}, message is ${n2.message}`);
425            return false;
426        }
427    }
428
429    initDomainCheckLog() {
430        try {
431            let a9 = this.getAppId();
432            let b9 = this.isCheckDomainBlockListAvailable();
433            console.debug('AtomicServiceWeb initDomainCheckLog appId=' + a9 + ' checkDomainBlockListAvailable=' + b9);
434        } catch (z8) {
435            console.error('AtomicServiceWeb initDomainCheckLog error, message: ' + z8.message);
436        }
437    }
438
439    getAppId() {
440        let x8 = this.context.abilityInfo.bundleName;
441        if (!x8) {
442            return null;
443        }
444        let y8 = x8.split('.');
445        if (!y8 || y8.length <= 0) {
446            return null;
447        }
448        return y8[y8.length - 1];
449    }
450
451    isMainPageOrIframeRequest(m8, w8) {
452        if (m8) {
453            return true;
454        }
455        if (w8 === webView.WebResourceType.MAIN_FRAME ||
456            w8 === webView.WebResourceType.SUB_FRAME) {
457            return true;
458        }
459        return false;
460    }
461
462    isCheckDomainBlockListAvailable() {
463        if (!atomicBasicEngine || !atomicBasicEngine.default) {
464            return false;
465        }
466        return typeof atomicBasicEngine.default.checkDomainBlockList === 'function';
467    }
468
469    interceptUrl(s8, t8, u8) {
470        if (!s8) {
471            return false;
472        }
473        if (s8.startsWith(RESOURCE_RAWFILE)) {
474            return true;
475        }
476        if (this.isMainPageOrIframeRequest(t8, u8)) {
477            return this.checkUrl(s8);
478        }
479        if (this.isCheckDomainBlockListAvailable()) {
480            return this.checkUrlNew(s8);
481        }
482        return true;
483    }
484
485    checkUrlNew(n8) {
486        let o8 = this.getAppId();
487        if (!o8) {
488            console.error('AtomicServiceWeb checkUrlNew error, appId is invalid');
489            return false;
490        }
491        try {
492            let q8 = this.cutUrl(n8);
493            let r8 = atomicBasicEngine.default.checkDomainBlockList(q8, o8);
494            console.debug(`AtomicServiceWeb checkUrlNew ret=${!r8} url=${q8}`);
495            return !r8;
496        } catch (p8) {
497            console.error(`AtomicServiceWeb checkUrlNew error, code: ${p8.code}, message: ${p8.message}`);
498            return true;
499        }
500    }
501
502    interceptOverrideUrlLoading(m8) {
503        if (!m8) {
504            return false;
505        }
506        if (m8.startsWith(TEL_PROTOCOL)) {
507            this.openMakeCall(m8);
508            return false;
509        }
510        if (m8.startsWith(MAILTO_PROTOCOL)) {
511            this.openSendMail(m8);
512            return false;
513        }
514        return this.checkUrl(m8);
515    }
516
517    openMakeCall(i8) {
518        if (!i8 || !i8.startsWith(TEL_PROTOCOL)) {
519            return;
520        }
521        try {
522            let k8 = i8.substring(TEL_PROTOCOL.length);
523            call.makeCall(k8).catch((l8) => {
524                console.error(`AtomicServiceWeb openMakeCall error, code: ${l8.code}, message: ${l8.message}`);
525            });
526        } catch (j8) {
527            console.error(`AtomicServiceWeb openMakeCall error, code: ${j8.code}, message: ${j8.message}`);
528        }
529    }
530
531    openSendMail(f8) {
532        if (!f8 || !f8.startsWith(MAILTO_PROTOCOL)) {
533            return;
534        }
535        try {
536            this.context.startAbility({
537                action: WANT_ACTION_SEND_TO_DATA,
538                uri: f8
539            }).catch((h8) => {
540                console.error(`AtomicServiceWeb openSendMail error, code: ${h8.code}, message: ${h8.message}`);
541            });
542        } catch (g8) {
543            console.error(`AtomicServiceWeb openSendMail error, code: ${g8.code}, message: ${g8.message}`);
544        }
545    }
546
547    handleOnPermissionRequest(t8) {
548        if (this.checkPermissionRequest(t8)) {
549            t8.request.grant(t8.request.getAccessibleResource());
550        } else {
551            t8.request.deny();
552        }
553    }
554
555    checkPermissionRequest(o8) {
556        let p8 = o8.request.getAccessibleResource();
557        if (!p8 || p8.length <= 0) {
558            return false;
559        }
560        let q8 = this.getAppId();
561        if (!q8) {
562            console.error('AtomicServiceWeb checkPermissionRequest error, appId is invalid');
563            return false;
564        }
565        for (let r8 of p8) {
566            let s8 = WEB_PERMISSIONS[r8];
567            if (!s8) {
568                console.error('AtomicServiceWeb checkPermissionRequest error, permission is not support');
569                return false;
570            }
571            if (!this.isPermissionUserGranted(s8)) {
572                return false;
573            }
574            if (!this.isPermissionWhiteListAllow(q8, s8)) {
575                return false;
576            }
577        }
578        return true;
579    }
580
581    isPermissionUserGranted(j8) {
582        try {
583            let l8 = bundleManager.getBundleInfoForSelfSync(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
584            if (!l8?.appInfo?.accessTokenId) {
585                return false;
586            }
587            let m8 = l8.appInfo.accessTokenId;
588            let n8 = abilityAccessCtrl.createAtManager()
589                .checkAccessTokenSync(m8, j8);
590            if (n8 !== abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
591                console.error(`AtomicServiceWeb isPermissionGranted permission ${j8} is not grant`);
592                return false;
593            }
594            return true;
595        } catch (k8) {
596            console.error(`AtomicServiceWeb isPermissionGranted error, code: ${k8.code}, message: ${k8.message}`);
597            return false;
598        }
599    }
600
601    isPermissionWhiteListAllow(f8, g8) {
602        if (!atomicBasicEngine || !atomicBasicEngine.default ||
603            typeof atomicBasicEngine.default.checkAtomicServiceAllow !== 'function') {
604            console.error('AtomicServiceWeb isPermissionRequestAllow error, checkAtomicServiceAllow is not available');
605            return false;
606        }
607        try {
608            let i8 = atomicBasicEngine.default.checkAtomicServiceAllow(f8, g8, TYPE_AS_WEB);
609            console.debug(`AtomicServiceWeb isPermissionRequestAllow ret=${i8} permission=${g8}`);
610            return i8;
611        } catch (h8) {
612            console.error(`AtomicServiceWeb isPermissionRequestAllow error, code: ${h8.code}, message: ${h8.message}`);
613            return false;
614        }
615    }
616
617    rerender() {
618        this.updateDirtyElements();
619    }
620}
621let AtomicServiceWebController = class AtomicServiceWebController {
622    setWebviewController(l5) {
623        this.webViewController = l5;
624    }
625
626    checkWebviewController() {
627        if (!this.webViewController) {
628            const d5 = {
629                name: '',
630                message: 'Init error. The AtomicServiceWebController must be associated with a AtomicServiceWeb component.',
631                code: 17100001,
632            };
633            throw d5;
634        }
635    }
636
637    getUserAgent() {
638        this.checkWebviewController();
639        return this.webViewController?.getUserAgent();
640    }
641
642    getCustomUserAgent() {
643        this.checkWebviewController();
644        return this.webViewController?.getCustomUserAgent();
645    }
646
647    setCustomUserAgent(z4) {
648        this.checkWebviewController();
649        this.webViewController?.setCustomUserAgent(z4);
650    }
651
652    accessForward() {
653        this.checkWebviewController();
654        return this.webViewController?.accessForward();
655    }
656
657    accessBackward() {
658        this.checkWebviewController();
659        return this.webViewController?.accessBackward();
660    }
661
662    accessStep(d4) {
663        this.checkWebviewController();
664        return this.webViewController?.accessStep(d4);
665    }
666
667    forward() {
668        this.checkWebviewController();
669        this.webViewController?.forward();
670    }
671
672    backward() {
673        this.checkWebviewController();
674        this.webViewController?.backward();
675    }
676
677    refresh() {
678        this.checkWebviewController();
679        this.webViewController?.refresh();
680    }
681
682    loadUrl(t3, y3) {
683        this.checkWebviewController();
684        if (y3) {
685            this.webViewController?.loadUrl(t3, y3);
686        } else {
687            this.webViewController?.loadUrl(t3);
688        }
689    }
690};
691AtomicServiceWebController = __decorate([
692    Observed
693], AtomicServiceWebController);
694
695export { AtomicServiceWebController };
696
697class AtomicServiceProxy {
698    constructor(z9) {
699        this.atomicService = z9;
700    }
701    invokeJsApi(apiNameAlias, options) {
702        try {
703            this.atomicService.reportBeginEvent(apiNameAlias);
704            options = options || {};
705            if (options instanceof Object) {
706                options.apiNameAlias = apiNameAlias;
707            }
708            if (!apiNameAlias || !ATOMIC_SERVICE_JS_API_MAP.has(apiNameAlias)) {
709                this.atomicService.errorWithCodeAndMsg(JS_API_INVALID_INVOKE_ERROR, options);
710                return;
711            }
712            let jsApiConfig = ATOMIC_SERVICE_JS_API_MAP.get(apiNameAlias);
713            if (!this.atomicService.checkRequiredFieldInOptions(jsApiConfig, options)) {
714                return;
715            }
716            let atomicService = this.atomicService;
717            atomicService[jsApiConfig?.apiName](options);
718        }
719        catch (err) {
720            this.atomicService.error(err, options);
721        }
722    }
723}
724
725class AtomicService {
726    constructor(q9, r9, s9) {
727        this.messageDataList = [];
728        this.onMessage = () => {
729        };
730        this.context = q9;
731        this.navPathStack = r9;
732        this.onMessage = s9 ? s9 : this.onMessage;
733    }
734
735    success(o9, p9) {
736        this.reportSuccessEvent(p9.apiNameAlias);
737        try {
738            p9?.callback && p9?.callback(undefined, o9);
739        } catch (f3) {
740            this.consoleError(`callback error, code is ${f3.code}, message is ${f3.message}`);
741        }
742    }
743
744    error(m9, n9) {
745        this.reportFailEvent(n9.apiNameAlias, m9.code);
746        try {
747            n9?.callback && n9?.callback(new AsError(m9.code ? m9.code : SYSTEM_INTERNAL_ERROR.code,
748                m9.message ? m9.message : SYSTEM_INTERNAL_ERROR.message));
749        } catch (a3) {
750            this.consoleError(`callback error, code is ${a3.code}, message is ${a3.message}`);
751        }
752    }
753
754    errorWithCodeAndMsg(k9, l9) {
755        this.reportFailEvent(l9.apiNameAlias, k9.code);
756        try {
757            l9?.callback && l9?.callback(k9);
758        } catch (u2) {
759            this.consoleError(`callback error, code is ${u2.code}, message is ${u2.message}`);
760        }
761    }
762
763    consoleLog(j9) {
764        if (LOG_ENABLE) {
765            console.log(`${LOG_PREFIX} ${j9}`);
766        }
767    }
768
769    consoleError(i9) {
770        if (LOG_ENABLE) {
771            console.error(`${LOG_PREFIX} ${i9}`);
772        }
773    }
774
775    logOptions(g9, h9) {
776        this.consoleLog(`${g9} options=${JSON.stringify(h9)}`);
777    }
778
779    checkParamRequired(d9, e9, f9) {
780        if (e9 === undefined || e9 === null || e9 === '') {
781            this.errorWithCodeAndMsg(new AsError(PARAM_REQUIRED_ERROR_CODE, `Param ${d9} is required.`), f9);
782            return false;
783        }
784        return true;
785    }
786
787    checkNumberParamPositive(a9, b9, c9) {
788        if (b9 <= 0) {
789            this.errorWithCodeAndMsg(new AsError(PARAM_NUMBER_POSITIVE_ERROR_CODE,
790                `Param ${a9} must be a positive number.`), c9);
791            return false;
792        }
793        return true;
794    }
795
796    checkRequiredFieldInOptions(v8, w8) {
797        if (!v8) {
798            return false;
799        }
800        if (!v8.requiredFieldNames) {
801            return true;
802        }
803        let x8 = w8;
804        for (let y8 = 0; y8 < v8.requiredFieldNames.length; y8++) {
805            let z8 = v8.requiredFieldNames[y8];
806            if (!this.checkParamRequired(z8, x8[z8], w8)) {
807                return false;
808            }
809        }
810        return true;
811    }
812
813    checkRouterMode(t8, u8) {
814        if (!t8 || t8 === 'Single' || t8 === 'Standard') {
815            return true;
816        }
817        this.errorWithCodeAndMsg(ROUTER_PARAM_MODE_INVALID_ERROR, u8);
818        return false;
819    }
820
821    parseRouterMode(s8) {
822        return s8 === 'Single' ? router.RouterMode.Single : router.RouterMode.Standard;
823    }
824
825    getRouterIndexByDelta(o8) {
826        let p8 = Number.parseInt(router.getLength());
827        for (let q8 = p8; q8 > 0; q8--) {
828            let r8 = router.getStateByIndex(q8);
829            if (r8?.name && o8-- == 0) {
830                return q8;
831            }
832        }
833        return 1;
834    }
835
836    checkBackUrlExists(i8, j8) {
837        let k8 = Number.parseInt(router.getLength());
838        for (let l8 = k8; l8 > 0; l8--) {
839            let m8 = router.getStateByIndex(l8);
840            if (m8?.name) {
841                let n8 = m8?.path + m8?.name;
842                if (n8 === i8) {
843                    return true;
844                }
845            }
846        }
847        this.errorWithCodeAndMsg(BACK_URL_NOT_EXIST_OR_OPENED_ERROR, j8);
848        return false;
849    }
850
851    checkNavPathStack(g8, h8) {
852        if (!this.navPathStack) {
853            this.errorWithCodeAndMsg(new AsError(NAV_PATH_STACK_NOT_EXIST_ERROR_CODE,
854                `Current page is not NavDestination, not support ${g8}().`), h8);
855            return false;
856        }
857        return true;
858    }
859
860    getNavPathIndexByDelta(e8) {
861        let f8 = this.navPathStack?.getAllPathName();
862        if (!f8 || f8.length == 0) {
863            return -1;
864        }
865        return f8.length > e8 ? (f8.length - e8 - 1) : -1;
866    }
867
868    onPopHandler(c8, d8) {
869        if (!c8?.info || !d8) {
870            return;
871        }
872        d8(new OnPopEvent(c8.info.name, c8.info.param, c8.result));
873    }
874
875    getCurrentNavPathInfo() {
876        let a8 = this.navPathStack?.getAllPathName();
877        let b8 = (a8 && a8.length > 0) ?
878            new NavPathInfo(a8[a8.length - 1], a8.length - 1) : new NavPathInfo(undefined, -1);
879        if (b8.index >= 0) {
880            b8.param = this.navPathStack?.getParamByIndex(b8.index);
881        }
882        return b8;
883    }
884
885    notifyMessage() {
886        if (this.messageDataList.length <= 0) {
887            return;
888        }
889        try {
890            this.onMessage(new OnMessageEvent(this.messageDataList));
891        } catch (q2) {
892            this.consoleError(`onMessage failed, code is ${q2.code}, message is ${q2.message}`);
893        }
894        this.messageDataList = [];
895    }
896
897    isJsApiEnable(z7) {
898        if (!z7) {
899            return false;
900        }
901        if (this.compareVersion(z7.minVersion, ATOMIC_SERVICE_JS_SDK_CURRENT_VERSION) &&
902        this.compareVersion(ATOMIC_SERVICE_JS_SDK_CURRENT_VERSION, z7.maxVersion)) {
903            return true;
904        }
905        return false;
906    }
907
908    compareVersion(p7, q7) {
909        if (!p7 || !q7) {
910            return false;
911        }
912        let r7 = p7.split('.').map(y7 => Number.parseInt(y7));
913        let s7 = q7.split('.').map(x7 => Number.parseInt(x7));
914        const t7 = Math.max(r7.length, s7.length);
915        for (let w7 = 0; w7 < t7; w7++) {
916            if (r7[w7] < s7[w7]) {
917                return true;
918            } else if (r7[w7] > s7[w7]) {
919                return false;
920            }
921        }
922        if (r7.length < s7.length) {
923            return true;
924        }
925        if (r7.length > s7.length) {
926            return false;
927        }
928        return true;
929    }
930
931    getUri(o7) {
932        if (!o7 || o7.startsWith('file://')) {
933            return o7;
934        }
935        return fileUri.getUriFromPath(o7);
936    }
937
938    async checkUploadFile(e7) {
939        if (!e7.files || e7.files.length <= 0) {
940            this.errorWithCodeAndMsg(UPLOAD_IMAGE_FILES_REQUIRED_ERROR, e7);
941            return new CheckUploadFileResult(false);
942        }
943        let f7 = new Map();
944        for (let g7 = 0; g7 < e7.files?.length; g7++) {
945            let h7 = e7.files[g7];
946            if (!h7.uri) {
947                this.errorWithCodeAndMsg(UPLOAD_IMAGE_FILES_URI_REQUIRED_ERROR, e7);
948                return new CheckUploadFileResult(false);
949            }
950            if (!h7.uri.startsWith('file://') && !fs.accessSync(h7.uri, fs.AccessModeType.EXIST)) {
951                this.errorWithCodeAndMsg(new AsError(UPLOAD_IMAGE_FILE_NOT_EXIST_ERROR_CODE,
952                    `File uri ${h7.uri} is not exist.`), e7);
953                return new CheckUploadFileResult(false);
954            }
955            let i7 = h7.uri;
956            let j7 = h7.uri;
957            if (j7.indexOf(UPLOAD_IMAGE_CACHE_DIR) < 0) {
958                let l7 = j7.startsWith('file://') ? j7 : fileUri.getUriFromPath(h7.uri);
959                j7 = this.context.cacheDir + '/' + j7.substring(j7.lastIndexOf('/') + 1);
960                try {
961                    await fs.copy(l7, fileUri.getUriFromPath(j7));
962                } catch (x1) {
963                    this.errorWithCodeAndMsg(UPLOAD_FILE_ERROR, e7);
964                    return new CheckUploadFileResult(false);
965                }
966            }
967            h7.uri = 'internal://' + j7.substring(j7.indexOf(UPLOAD_IMAGE_CACHE_DIR) + 1);
968            f7.set(j7, i7);
969        }
970        return new CheckUploadFileResult(true, f7);
971    }
972
973    convertToRequestData(a7) {
974        let b7 = [];
975        if (a7) {
976            a7.forEach(d7 => {
977                if (!d7.name || !d7.value) {
978                    return;
979                }
980                b7.push({ name: d7.name, value: d7.value });
981            });
982        }
983        return b7;
984    }
985
986    convertToFile(w6) {
987        let x6 = [];
988        if (w6) {
989            w6.forEach(z6 => {
990                x6.push({
991                    filename: z6.filename,
992                    name: z6.name,
993                    uri: z6.uri,
994                    type: z6.type
995                });
996            });
997        }
998        return x6;
999    }
1000
1001    handleUploadFileResult(p6, q6, r6) {
1002        let s6 = [];
1003        if (p6) {
1004            p6.forEach(u6 => {
1005                let v6 = u6.path ? q6.get(u6.path) : u6.path;
1006                s6.push(new UploadFileTaskState(v6 ? v6 : u6.path, u6.responseCode, u6.message));
1007            });
1008        }
1009        this.success(new UploadFileResult(s6), r6);
1010    }
1011
1012    parseFileNameFromUrl(m6) {
1013        if (!m6) {
1014            return '';
1015        }
1016        let n6 = m6.split('?')[0];
1017        if (n6.indexOf('/') < 0) {
1018            return '';
1019        }
1020        let o6 = n6.lastIndexOf('/');
1021        if (o6 == (n6.length - 1)) {
1022            return '';
1023        }
1024        return n6.substring(o6 + 1);
1025    }
1026
1027    checkAccessToken(v5) {
1028        let w5 = bundleManager.getBundleInfoForSelfSync(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
1029        let x5 = w5.appInfo.accessTokenId;
1030        let y5 = abilityAccessCtrl.createAtManager();
1031        return y5.checkAccessToken(x5, v5);
1032    }
1033
1034    checkPermissions(j5, k5) {
1035        this.checkAccessToken(j5).then(o5 => {
1036            if (o5 == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
1037                k5(undefined);
1038            } else {
1039                let p5 = abilityAccessCtrl.createAtManager();
1040                p5.requestPermissionsFromUser(this.context, [j5]).then(t5 => {
1041                    for (let u5 = 0; u5 < t5.authResults.length; u5++) {
1042                        if (t5.authResults[u5] != 0) {
1043                            const error = {
1044                                name: '',
1045                                message: `RequestPermissionsFromUser error. authResult: ${t5.authResults[u5]}.`,
1046                                code: PERMISSION_LOCATION_USER_REFUSED_ERROR
1047                            };
1048                            k5(error);
1049                            return;
1050                        }
1051                    }
1052                    k5(undefined);
1053                }).catch((s5) => {
1054                    k5(s5);
1055                });
1056            }
1057        }).catch((n5) => {
1058            k5(n5);
1059        });
1060    }
1061    /**
1062     * 判断是否需要打点
1063     *
1064     * @param apiNameAlias 接口别名
1065     * @return 是否需要打点
1066     */
1067    isNeedReport(apiName) {
1068        return NEED_REPORTED_API_LIST.includes(apiName);
1069    }
1070    /**
1071     * 上报Api调用开始的打点
1072     *
1073     * @param apiNameAlias 接口别名
1074     */
1075    reportBeginEvent(apiNameAlias) {
1076        const apiName = `has.${apiNameAlias}`;
1077        if (this.isNeedReport(apiName)) {
1078            HiAnalyticsUtil.reportApiEvent(apiName, ActionState.BEGIN);
1079        }
1080    }
1081    /**
1082     * 上报Api调用成功的打点
1083     *
1084     * @param apiNameAlias 接口别名
1085     */
1086    reportSuccessEvent(apiNameAlias) {
1087        const apiName = `has.${apiNameAlias}`;
1088        if (this.isNeedReport(apiName)) {
1089            HiAnalyticsUtil.reportApiEvent(apiName, ActionState.SUCCESS);
1090        }
1091    }
1092    /**
1093     * 上报Api调用失败的打点
1094     *
1095     * @param apiNameAlias 接口别名
1096     * @param errCode 错误码
1097     */
1098    reportFailEvent(apiNameAlias, errCode) {
1099        const apiName = `has.${apiNameAlias}`;
1100        if (this.isNeedReport(apiName)) {
1101            HiAnalyticsUtil.reportApiEvent(apiName, ActionState.FAIL, errCode);
1102        }
1103    }
1104}
1105
1106class AtomicServiceApi extends AtomicService {
1107    constructor(g5, h5, i5) {
1108        super(g5, h5, i5);
1109    }
1110
1111    pushUrl(c5) {
1112        if (!this.checkRouterMode(c5.mode, c5)) {
1113            return;
1114        }
1115        router.pushUrl({ url: c5.url, params: c5.params }, this.parseRouterMode(c5.mode)).then(() => {
1116            this.success(new PushUrlResult(), c5);
1117        }).catch((f5) => {
1118            this.error(f5, c5);
1119        });
1120    }
1121
1122    replaceUrl(y4) {
1123        if (!this.checkRouterMode(y4.mode, y4)) {
1124            return;
1125        }
1126        router.replaceUrl({ url: y4.url, params: y4.params }, this.parseRouterMode(y4.mode)).then(() => {
1127            this.success(new ReplaceUrlResult(), y4);
1128        }).catch((b5) => {
1129            this.error(b5, y4);
1130        });
1131    }
1132
1133    backUrl(x4) {
1134        if (x4.url) {
1135            if (!this.checkBackUrlExists(x4.url, x4)) {
1136                return;
1137            }
1138            router.back({ url: x4.url, params: x4.params });
1139            this.success(new BackUrlResult(), x4);
1140        } else if (x4.index || x4.index === 0) {
1141            if (!this.checkNumberParamPositive('index', x4.index, x4)) {
1142                return;
1143            }
1144            router.back(x4.index, x4.params);
1145            this.success(new BackUrlResult(), x4);
1146        } else if (x4.delta || x4.delta === 0) {
1147            if (!this.checkNumberParamPositive('delta', x4.delta, x4)) {
1148                return;
1149            }
1150            router.back(this.getRouterIndexByDelta(x4.delta), x4.params);
1151            this.success(new BackUrlResult(), x4);
1152        } else {
1153            router.back();
1154            this.success(new BackUrlResult(), x4);
1155        }
1156    }
1157
1158    clearUrl(w4) {
1159        router.clear();
1160        this.success(new ClearUrlResult(), w4);
1161    }
1162
1163    pushPath(u4) {
1164        if (!this.checkNavPathStack('navPathStack.pushPath', u4)) {
1165            return;
1166        }
1167        this.navPathStack?.pushPath({
1168            name: u4.name,
1169            param: u4.param,
1170            onPop: v4 => this.onPopHandler(v4, u4.onPop)
1171        }, u4.animated);
1172        this.success(new PushPathResult(), u4);
1173    }
1174
1175    replacePath(s4) {
1176        if (!this.checkNavPathStack('navPathStack.replacePath', s4)) {
1177            return;
1178        }
1179        this.navPathStack?.replacePath({
1180            name: s4.name,
1181            param: s4.param,
1182            onPop: t4 => this.onPopHandler(t4, s4.onPop)
1183        }, s4.animated);
1184        this.success(new ReplacePathResult(), s4);
1185    }
1186
1187    popPath(p4) {
1188        if (!this.checkNavPathStack('navPathStack.pop', p4)) {
1189            return;
1190        }
1191        if (p4.name) {
1192            let r4 = this.navPathStack?.popToName(p4.name, p4.result, p4.animated);
1193            if (r4 === undefined || r4 === -1) {
1194                this.errorWithCodeAndMsg(POP_PATH_NAME_NOT_EXIST_ERROR, p4);
1195                return;
1196            }
1197        } else if (p4.index || p4.index === 0) {
1198            if (p4.index < -1) {
1199                this.errorWithCodeAndMsg(POP_PATH_PARAM_INDEX_INVALID_ERROR, p4);
1200                return;
1201            }
1202            if (p4.index > this.getCurrentNavPathInfo().index) {
1203                this.errorWithCodeAndMsg(POP_PATH_INDEX_OUT_OF_RANGE_ERROR, p4);
1204                return;
1205            }
1206            this.navPathStack?.popToIndex(p4.index, p4.result, p4.animated);
1207        } else if (p4.delta || p4.delta === 0) {
1208            if (!this.checkNumberParamPositive('delta', p4.delta, p4)) {
1209                return;
1210            }
1211            this.navPathStack?.popToIndex(this.getNavPathIndexByDelta(p4.delta), p4.result, p4.animated);
1212        } else {
1213            this.navPathStack?.pop(p4.result, p4.animated);
1214        }
1215        let q4 = this.getCurrentNavPathInfo();
1216        this.success(new PopPathResult(q4.name, q4.index, q4.param), p4);
1217    }
1218
1219    clearPath(o4) {
1220        if (!this.checkNavPathStack('navPathStack.clear', o4)) {
1221            return;
1222        }
1223        this.navPathStack?.clear(o4.animated);
1224        this.success(new ClearPathResult(), o4);
1225    }
1226
1227    postMessage(n4) {
1228        n4.data && this.messageDataList.push(n4.data);
1229        this.success(new PostMessageResult(), n4);
1230    }
1231
1232    getEnv(l4) {
1233        let m4 = new GetEnvResult();
1234        m4.deviceType = deviceInfo.deviceType;
1235        m4.brand = deviceInfo.brand;
1236        m4.productModel = deviceInfo.productModel;
1237        m4.osFullName = deviceInfo.osFullName;
1238        this.success(m4, l4);
1239    }
1240
1241    checkJsApi(h4) {
1242        let i4 = new Map();
1243        h4.jsApiList?.forEach(k4 => {
1244            i4[k4] = this.isJsApiEnable(ATOMIC_SERVICE_JS_API_MAP.get(k4));
1245        });
1246        this.success(new CheckJsApiResult(i4), h4);
1247    }
1248
1249    pickCamera(c4) {
1250        picker.pick(this.context, c4.mediaTypes, {
1251            cameraPosition: c4.cameraPosition,
1252            saveUri: c4.saveUri,
1253            videoDuration: c4.videoDuration
1254        }).then((g4) => {
1255            this.success(new PickCameraResult(g4.resultCode, g4.resultUri, g4.mediaType), c4);
1256        }).catch((f4) => {
1257            this.error(f4, c4);
1258        });
1259    }
1260
1261    selectPhoto(w3) {
1262        let x3 = new photoAccessHelper.PhotoViewPicker();
1263        x3.select({
1264            MIMEType: w3.mimeType,
1265            maxSelectNumber: w3.maxSelectNumber,
1266            isPhotoTakingSupported: w3.isPhotoTakingSupported,
1267            isEditSupported: w3.isEditSupported,
1268            isSearchSupported: w3.isSearchSupported,
1269            recommendationOptions: {
1270                recommendationType: w3.recommendationType
1271            },
1272            preselectedUris: w3.preselectedUris
1273        }).then((b4) => {
1274            this.success(new SelectPhotoResult(b4.photoUris, b4.isOriginalPhoto), w3);
1275        }).catch((a4) => {
1276            this.error(a4, w3);
1277        });
1278    }
1279
1280    openPreview(n3) {
1281        let o3 = this.getUri(n3.uri);
1282        filePreview.openPreview(this.context, {
1283            uri: o3,
1284            mimeType: n3.mimeType,
1285            title: n3.title
1286        }).then(() => {
1287            this.success(new OpenPreviewResult(), n3);
1288        }).catch((v3) => {
1289            this.error(v3, n3);
1290        });
1291    }
1292
1293    uploadFile(z2) {
1294        this.checkUploadFile(z2).then(d3 => {
1295            if (!d3.checkResult) {
1296                return;
1297            }
1298            let e3 = {
1299                url: z2.url,
1300                header: z2.header,
1301                method: z2.method,
1302                files: this.convertToFile(z2.files),
1303                data: this.convertToRequestData(z2.data)
1304            };
1305            request.uploadFile(this.context, e3).then((i3) => {
1306                i3.on('complete', (m3) => {
1307                    this.handleUploadFileResult(m3, d3.uriMap, z2);
1308                });
1309                i3.on('fail', (l3) => {
1310                    this.handleUploadFileResult(l3, d3.uriMap, z2);
1311                });
1312            }).catch((h3) => {
1313                this.error(h3, z2);
1314            });
1315        }).catch((c3) => {
1316            this.error(c3, z2);
1317        });
1318    }
1319
1320    downloadFile(m2) {
1321        let o2 = `${util.generateRandomUUID().replaceAll('-', '')}`;
1322        let p2 = `${this.context.cacheDir}/${o2}`;
1323        request.downloadFile(this.context, {
1324            url: m2.url,
1325            header: m2.header ? m2.header : new Object(),
1326            filePath: p2,
1327            enableMetered: m2.enableMetered,
1328            enableRoaming: m2.enableRoaming,
1329            networkType: m2.networkType,
1330            background: false
1331        }).then((t2) => {
1332            t2.on('complete', () => {
1333                this.success(new DownloadFileResult(p2), m2);
1334            });
1335            t2.on('fail', w2 => {
1336                this.errorWithCodeAndMsg(new AsError(w2, 'File download fail.'), m2);
1337            });
1338        }).catch((s2) => {
1339            this.error(s2, m2);
1340        });
1341    }
1342
1343    getNetworkType(c2) {
1344        connection.getDefaultNet().then(g2 => {
1345            if (!g2 || g2.netId === 0) {
1346                this.errorWithCodeAndMsg(NETWORK_NO_ACTIVE_ERROR, c2);
1347                return;
1348            }
1349            connection.getNetCapabilities(g2).then(k2 => {
1350                let l2 = new GetNetworkTypeResult(k2.bearerTypes, k2.networkCap, k2.linkUpBandwidthKbps,
1351                    k2.linkDownBandwidthKbps);
1352                this.success(l2, c2);
1353            }).catch((j2) => {
1354                this.error(j2, c2);
1355            });
1356        }).catch((f2) => {
1357            this.error(f2, c2);
1358        });
1359    }
1360
1361    getLocation(u1) {
1362        this.checkPermissions(PERMISSION_APPROXIMATELY_LOCATION, w1 => {
1363            if (w1) {
1364                this.error(w1, u1);
1365                return;
1366            }
1367            geoLocationManager.getCurrentLocation({
1368                priority: u1.priority,
1369                scenario: u1.scenario,
1370                maxAccuracy: u1.maxAccuracy,
1371                timeoutMs: u1.timeoutMs
1372            }).then(a2 => {
1373                let b2 =
1374                    new GetLocationResult(a2.latitude, a2.longitude, a2.altitude, a2.accuracy, a2.speed, a2.timeStamp,
1375                        a2.direction, a2.timeSinceBoot, a2.additions, a2.additionSize);
1376                this.success(b2, u1);
1377            }).catch((z1) => {
1378                this.error(z1, u1);
1379            });
1380        });
1381    }
1382
1383    login(c2) {
1384        let d2 = new authentication.HuaweiIDProvider().createLoginWithHuaweiIDRequest();
1385        d2.forceLogin = false;
1386        d2.state = util.generateRandomUUID();
1387        let e2 = new authentication.AuthenticationController();
1388        e2.executeRequest(d2).then((g2) => {
1389            if (!g2 || !g2.data) {
1390                this.errorWithCodeAndMsg(LOGIN_RESPONSE_DATA_NULL_ERROR, c2);
1391                return;
1392            }
1393            if (d2.state !== g2.state) {
1394                this.errorWithCodeAndMsg(LOGIN_STATE_INVALID_ERROR, c2);
1395                return;
1396            }
1397            this.success(new LoginResult(g2.data.openID, g2.data.unionID, g2.data.authorizationCode, g2.data.idToken),
1398                c2);
1399        }).catch((f2) => {
1400            this.error(f2, c2);
1401        });
1402    }
1403
1404    requestPayment(a2) {
1405        if (typeof a2.orderStr !== 'string') {
1406            this.errorWithCodeAndMsg(REQUEST_PAYMENT_ORDER_STR_INVALID_ERROR, a2);
1407            return;
1408        }
1409        paymentService.requestPayment(this.context, a2.orderStr).then(() => {
1410            this.success(new RequestPaymentResult(), a2);
1411        }).catch((b2) => {
1412            this.error(b2, a2);
1413        });
1414    }
1415}
1416
1417class NavPathInfo {
1418    constructor(s1, t1) {
1419        this.name = s1;
1420        this.index = t1;
1421    }
1422}
1423
1424class CheckUploadFileResult {
1425    constructor(q1, r1) {
1426        this.checkResult = q1;
1427        this.uriMap = r1;
1428    }
1429}
1430
1431class BaseOptions {
1432}
1433
1434class PushUrlOptions extends BaseOptions {
1435}
1436
1437class PushUrlResult {
1438}
1439
1440class ReplaceUrlOptions extends BaseOptions {
1441}
1442
1443class ReplaceUrlResult {
1444}
1445
1446class BackUrlOptions extends BaseOptions {
1447}
1448
1449class BackUrlResult {
1450}
1451
1452class ClearUrlOptions extends BaseOptions {
1453}
1454
1455class ClearUrlResult {
1456}
1457
1458class OnPopEvent {
1459    constructor(n1, o1, p1) {
1460        this.name = n1;
1461        this.param = o1;
1462        this.result = p1;
1463    }
1464}
1465
1466class PushPathOptions extends BaseOptions {
1467}
1468
1469class PushPathResult {
1470}
1471
1472class ReplacePathOptions extends BaseOptions {
1473}
1474
1475class ReplacePathResult {
1476}
1477
1478class PopPathOptions extends BaseOptions {
1479}
1480
1481class PopPathResult {
1482    constructor(k1, l1, m1) {
1483        this.name = k1;
1484        this.index = l1;
1485        this.param = m1;
1486    }
1487}
1488
1489class ClearPathOptions extends BaseOptions {
1490}
1491
1492class ClearPathResult {
1493}
1494
1495class PostMessageOptions extends BaseOptions {
1496}
1497
1498class PostMessageResult {
1499}
1500
1501export class OnMessageEvent {
1502    constructor(j1) {
1503        this.data = j1;
1504    }
1505}
1506
1507export class OnErrorReceiveEvent {
1508    constructor(h1, i1) {
1509        this.request = h1;
1510        this.error = i1;
1511    }
1512}
1513
1514export class OnHttpErrorReceiveEvent {
1515    constructor(f1, g1) {
1516        this.request = f1;
1517        this.response = g1;
1518    }
1519}
1520
1521export class OnPageBeginEvent {
1522    constructor(e1) {
1523        this.url = e1;
1524    }
1525}
1526
1527export class OnPageEndEvent {
1528    constructor(d1) {
1529        this.url = d1;
1530    }
1531}
1532
1533export class WebHeader {
1534    constructor(j3, p3) {
1535        this.headerKey = j3;
1536        this.headerValue = p3;
1537    }
1538}
1539
1540class GetEnvOptions extends BaseOptions {
1541}
1542
1543class GetEnvResult {
1544}
1545
1546class CheckJsApiOptions extends BaseOptions {
1547}
1548
1549class CheckJsApiResult {
1550    constructor(c1) {
1551        this.checkResult = c1;
1552    }
1553}
1554
1555class PickCameraOptions extends BaseOptions {
1556}
1557
1558class PickCameraResult {
1559    constructor(z, a1, b1) {
1560        this.resultCode = z;
1561        this.resultUri = a1;
1562        this.mediaType = b1;
1563    }
1564}
1565
1566class SelectPhotoOptions extends BaseOptions {
1567}
1568
1569class SelectPhotoResult {
1570    constructor(x, y) {
1571        this.photoUris = x;
1572        this.isOriginalPhoto = y;
1573    }
1574}
1575
1576class OpenPreviewOptions extends BaseOptions {
1577}
1578
1579class OpenPreviewResult {
1580}
1581
1582class UploadFileOptions extends BaseOptions {
1583}
1584
1585class UploadFile {
1586    constructor(t, u, v, w) {
1587        this.filename = t;
1588        this.name = u;
1589        this.uri = v;
1590        this.type = w;
1591    }
1592}
1593
1594class UploadRequestData {
1595}
1596
1597class UploadFileResult {
1598    constructor(s) {
1599        this.taskStates = s;
1600    }
1601}
1602
1603class UploadFileTaskState {
1604    constructor(p, q, r) {
1605        this.path = p;
1606        this.responseCode = q;
1607        this.message = r;
1608    }
1609}
1610
1611class DownloadFileOptions extends BaseOptions {
1612}
1613
1614class DownloadFileResult {
1615    constructor(o) {
1616        this.uri = o;
1617    }
1618}
1619
1620class GetNetworkTypeOptions extends BaseOptions {
1621}
1622
1623class GetNetworkTypeResult {
1624    constructor(k, l, m, n) {
1625        this.bearerTypes = k;
1626        this.networkCap = l;
1627        this.linkUpBandwidthKbps = m;
1628        this.linkDownBandwidthKbps = n;
1629    }
1630}
1631
1632class GetLocationOptions extends BaseOptions {
1633}
1634
1635class GetLocationResult {
1636    constructor(a, b, c, d, e, f, g, h, i, j) {
1637        this.latitude = a;
1638        this.longitude = b;
1639        this.altitude = c;
1640        this.accuracy = d;
1641        this.speed = e;
1642        this.timeStamp = f;
1643        this.direction = g;
1644        this.timeSinceBoot = h;
1645        this.additions = i;
1646        this.additionSize = j;
1647    }
1648}
1649
1650class LoginOptions extends BaseOptions {
1651}
1652
1653class LoginResult {
1654    constructor(a, b, c, d) {
1655        this.code = c;
1656        this.idToken = d;
1657        this.openID = a;
1658        this.unionID = b;
1659    }
1660}
1661
1662class RequestPaymentOptions extends BaseOptions {
1663}
1664
1665class RequestPaymentResult {
1666}
1667
1668class HiAnalyticsUtil {
1669    /**
1670     * 打点数据上报
1671     *
1672     * @param time 时间戳
1673     * @param content 打点参数json字符串
1674     */
1675    static writeEndEvent(time, content) {
1676        console.info(`writeEndEvent ->  time: ${time} ,content: ${content} `);
1677        let event = {
1678            domain: 'api_diagnostic',
1679            name: 'api_exec_end',
1680            params: {
1681                api_name: 'ascf',
1682                sdk_name: 'atomicservice_web',
1683                begin_time: time,
1684                // 调用次数
1685                call_times: 3,
1686                // 调用成功次数
1687                success_times: 1,
1688                contents: content
1689            },
1690            eventType: hiAppEvent.EventType.BEHAVIOR
1691        };
1692        hiAppEvent.write(event);
1693    }
1694    /**
1695     * 应用的唯一标识
1696     */
1697    static initAnalytics() {
1698        if (!HiAnalyticsUtil.processorId) {
1699            HiAnalyticsUtil.addEventProcessor();
1700        }
1701        if (HiAnalyticsUtil.appIdentifier && HiAnalyticsUtil.runningMode) {
1702            return;
1703        }
1704        let bundleInfo = bundleManager.getBundleInfoForSelfSync(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO |
1705            bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
1706        HiAnalyticsUtil.appIdentifier = bundleInfo.signatureInfo.appIdentifier;
1707        HiAnalyticsUtil.runningMode = bundleInfo.appInfo.appProvisionType;
1708    }
1709    /**
1710     * 添加处理者
1711     */
1712    static addEventProcessor() {
1713        let processor = {
1714            name: 'ha_app_event',
1715            appId: 'com_huawei_hmos_sdk_ocg',
1716            routeInfo: 'AUTO',
1717            eventConfigs: [
1718                {
1719                    domain: 'api_diagnostic',
1720                    name: 'api_exec_end',
1721                    isRealTime: false
1722                },
1723                {
1724                    domain: 'api_diagnostic',
1725                    name: 'api_called_stat',
1726                    isRealTime: true
1727                },
1728                {
1729                    domain: 'api_diagnostic',
1730                    name: 'api_called_stat_cnt',
1731                    isRealTime: true
1732                },
1733            ],
1734            periodReport: 90,
1735            batchReport: 30
1736        };
1737        return hiAppEvent.addProcessor(processor);
1738    }
1739    /**
1740     * asweb jssdk API数据打点业务处理
1741     *
1742     * @param apiName 接口名
1743     * @param actionState 接口调用状态
1744     * @param errorNumber 错误码
1745     */
1746    static reportApiEvent(apiName, actionState, errorNumber) {
1747        try {
1748            if (!apiName || !actionState) {
1749                return;
1750            }
1751            HiAnalyticsUtil.initAnalytics();
1752            const ascfAction = 'APICaller_' + apiName;
1753            const content = JSON.stringify({
1754                appIdentify: HiAnalyticsUtil.appIdentifier,
1755                ascfVersionName: deviceInfo.displayVersion,
1756                runningMode: HiAnalyticsUtil.runningMode,
1757                ascfAction,
1758                caller: 'ASWeb',
1759                actionState,
1760                errorNumber
1761            });
1762            HiAnalyticsUtil.writeEndEvent(new Date().getTime(), content);
1763        }
1764        catch (err) {
1765            console.error(`reportApiEvent -> reportApiEvent error, message: ${err.message}`);
1766        }
1767    }
1768    /**
1769     * asweb 组件创建打点
1770     *
1771     * @param apiName 接口名
1772     * @param actionState 接口调用状态
1773     * @param errorNumber 错误码
1774     */
1775    static reportComponentEvent() {
1776        try {
1777            HiAnalyticsUtil.initAnalytics();
1778            const content = JSON.stringify({
1779                appIdentify: HiAnalyticsUtil.appIdentifier,
1780                ascfVersionName: deviceInfo.displayVersion,
1781                runningMode: HiAnalyticsUtil.runningMode,
1782                caller: 'ASWeb',
1783            });
1784            HiAnalyticsUtil.writeEndEvent(new Date().getTime(), content);
1785        }
1786        catch (err) {
1787            console.error(`reportComponentEvent -> reportComponentEvent error, message: ${err.message}`);
1788        }
1789    }
1790}
1791HiAnalyticsUtil.processorId = undefined;
1792/**
1793 * 数据打点的接口状态
1794 */
1795const ActionState = {
1796    BEGIN: 'begin',
1797    SUCCESS: 'success',
1798    FAIL: 'fail'
1799}
1800//# sourceMappingURL=atomicserviceweb.js.map
1801export default {
1802    AtomicServiceWeb,
1803    AtomicServiceWebController
1804}
1805