ota-native-bridge 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,10 @@
1
+ /**
2
+ * `<script src="ota-native-bridge.js">` 全局 API 类型。
3
+ */
4
+ import type { Native as NativeApi } from './dist/native';
5
+
6
+ declare global {
7
+ const Native: typeof NativeApi;
8
+ }
9
+
10
+ export {};
@@ -0,0 +1,399 @@
1
+ /**
2
+ * 跨平台 Native Bridge(iOS / Android / HarmonyOS)
3
+ * npm 包名:ota-native-bridge
4
+ * 全局:window.Native
5
+ */
6
+ (function (global) {
7
+ var pending = {};
8
+ var seq = 0;
9
+ var readyPromise = null;
10
+
11
+ function getNativeMessenger() {
12
+ if (global.AndroidBridge && global.AndroidBridge.postMessage) {
13
+ return function (msg) { global.AndroidBridge.postMessage(msg); };
14
+ }
15
+ if (global.webkit && global.webkit.messageHandlers && global.webkit.messageHandlers.IOSBridge) {
16
+ return function (msg) { global.webkit.messageHandlers.IOSBridge.postMessage(msg); };
17
+ }
18
+ if (global.HarmonyBridge && global.HarmonyBridge.postMessage) {
19
+ return function (msg) { global.HarmonyBridge.postMessage(msg); };
20
+ }
21
+ return null;
22
+ }
23
+
24
+ function callNative(method, params) {
25
+ return new Promise(function (resolve, reject) {
26
+ var post = getNativeMessenger();
27
+ if (!post) {
28
+ reject(new Error('Native bridge not available'));
29
+ return;
30
+ }
31
+ var id = 'cb_' + ++seq;
32
+ pending[id] = { resolve: resolve, reject: reject };
33
+ post(JSON.stringify({ id: id, method: method, params: params || {} }));
34
+ });
35
+ }
36
+
37
+ global.__nativeBridgeCallback = function (id, success, payload) {
38
+ var item = pending[id];
39
+ if (!item) return;
40
+ delete pending[id];
41
+ if (success) {
42
+ try {
43
+ var data = typeof payload === 'string' ? JSON.parse(payload) : payload;
44
+ item.resolve(data);
45
+ } catch (e) {
46
+ item.resolve(payload);
47
+ }
48
+ } else {
49
+ item.reject(new Error(typeof payload === 'string' ? payload : String(payload)));
50
+ }
51
+ };
52
+
53
+ function waitForBridge(maxMs) {
54
+ maxMs = maxMs || 8000;
55
+ if (typeof document === 'undefined') {
56
+ return Promise.reject(new Error('Not in browser'));
57
+ }
58
+ if (getNativeMessenger()) {
59
+ return Promise.resolve();
60
+ }
61
+ if (readyPromise) {
62
+ return readyPromise;
63
+ }
64
+ readyPromise = new Promise(function (resolve, reject) {
65
+ var timer = setTimeout(function () {
66
+ readyPromise = null;
67
+ document.removeEventListener('nativebridgeready', onReady);
68
+ reject(new Error('Bridge timeout'));
69
+ }, maxMs);
70
+ function onReady() {
71
+ clearTimeout(timer);
72
+ resolve();
73
+ }
74
+ document.addEventListener('nativebridgeready', onReady, { once: true });
75
+ });
76
+ return readyPromise;
77
+ }
78
+
79
+ function invokeNative(method, params) {
80
+ return waitForBridge().then(function () { return callNative(method, params); });
81
+ }
82
+
83
+ function withCallback(promise, callback) {
84
+ if (typeof callback === 'function') {
85
+ promise
86
+ .then(function (result) { callback(result); })
87
+ .catch(function (error) { callback(undefined, error instanceof Error ? error : new Error(String(error))); });
88
+ }
89
+ return promise;
90
+ }
91
+
92
+ function getPlatform() {
93
+ if (global.AndroidBridge && global.AndroidBridge.postMessage) return 'android';
94
+ if (global.webkit && global.webkit.messageHandlers && global.webkit.messageHandlers.IOSBridge) return 'ios';
95
+ if (global.HarmonyBridge && global.HarmonyBridge.postMessage) return 'harmony';
96
+ return 'web';
97
+ }
98
+
99
+ function isNativePlatform() {
100
+ return getPlatform() !== 'web';
101
+ }
102
+
103
+ var App = {
104
+ ping: function (cb) { return withCallback(invokeNative('ping'), cb); },
105
+ getInfo: function (cb) { return withCallback(invokeNative('getAppInfo'), cb); },
106
+ getChannelCodes: function (cb) { return withCallback(invokeNative('getAppChannelCodes'), cb); },
107
+ launch: function (opts, cb) { return withCallback(invokeNative('launchApp', opts), cb); },
108
+ isInstalled: function (packageName, cb) { return withCallback(invokeNative('isAppInstalled', { packageName: packageName }), cb); },
109
+ checkInstalled: function (packageNames, cb) { return withCallback(invokeNative('checkAppsInstalled', { packageNames: packageNames }), cb); }
110
+ };
111
+
112
+ var Device = {
113
+ getInfo: function (cb) { return withCallback(invokeNative('getDeviceInfo'), cb); },
114
+ getScreenInfo: function (cb) { return withCallback(invokeNative('getScreenInfo'), cb); },
115
+ getOrientation: function (cb) { return withCallback(invokeNative('getOrientation'), cb); },
116
+ getLockStatus: function (cb) { return withCallback(invokeNative('getLockStatus'), cb); },
117
+ getSystemInfo: function (cb) { return withCallback(invokeNative('getSystemInfo'), cb); }
118
+ };
119
+
120
+ var Config = {
121
+ getNativeConfig: function (cb) { return withCallback(invokeNative('getNativeConfig'), cb); },
122
+ setNativeFeatures: function (opts, cb) { return withCallback(invokeNative('setNativeFeatures', opts), cb); }
123
+ };
124
+
125
+ var Theme = {
126
+ get: function (cb) { return withCallback(invokeNative('getAppTheme'), cb); },
127
+ set: function (opts, cb) { return withCallback(invokeNative('setAppTheme', opts), cb); }
128
+ };
129
+
130
+ var Icon = {
131
+ list: function (cb) { return withCallback(invokeNative('getAppIcons'), cb); },
132
+ get: function (cb) { return withCallback(invokeNative('getAppIcon'), cb); },
133
+ set: function (opts, cb) { return withCallback(invokeNative('setAppIcon', opts), cb); },
134
+ setFromUrl: function (opts, cb) { return withCallback(invokeNative('setAppIconFromUrl', opts), cb); },
135
+ setFromBase64: function (opts, cb) { return withCallback(invokeNative('setAppIconFromBase64', opts), cb); }
136
+ };
137
+
138
+ var Viewport = {
139
+ getSafeAreaInsets: function (cb) { return withCallback(invokeNative('getSafeAreaInsets'), cb); },
140
+ getWindowInfo: function (cb) { return withCallback(invokeNative('getWindowInfo'), cb); },
141
+ refreshSafeArea: function (cb) { return withCallback(invokeNative('refreshSafeArea'), cb); }
142
+ };
143
+
144
+ var Notification = {
145
+ show: function (opts, cb) { return withCallback(invokeNative('showNotification', opts), cb); },
146
+ setBadgeCount: function (count, cb) { return withCallback(invokeNative('setBadgeCount', { count: count }), cb); }
147
+ };
148
+
149
+ var Ota = {
150
+ checkResourceUpdate: function (url, cb) { return withCallback(invokeNative('checkResourceUpdate', url ? { url: url } : {}), cb); },
151
+ applyResourceUpdate: function (url, cb) { return withCallback(invokeNative('applyResourceUpdate', { url: url }), cb); },
152
+ installResourcePackage: function (opts, cb) { return withCallback(invokeNative('installResourcePackage', opts || {}), cb); },
153
+ checkApkUpdate: function (url, cb) { return withCallback(invokeNative('checkApkUpdate', url ? { url: url } : {}), cb); },
154
+ installAppPackage: function (opts, cb) { return withCallback(invokeNative('installAppPackage', opts || {}), cb); },
155
+ checkUpdate: function (uidOrOpts, cb) {
156
+ var opts = typeof uidOrOpts === 'string' ? { uid: uidOrOpts } : (uidOrOpts || {});
157
+ return withCallback(invokeNative('checkAppUpdate', {
158
+ notifyWhenNoUpdate: opts.notifyWhenNoUpdate !== false,
159
+ uid: opts.uid || ''
160
+ }), cb);
161
+ },
162
+ check: function (uid, cb) {
163
+ if (!uid) return Ota.checkUpdate(undefined, cb);
164
+ return withCallback(invokeNative('setOtaUid', { uid: uid }).then(function () {
165
+ return invokeNative('checkAppUpdate', { notifyWhenNoUpdate: true, uid: uid });
166
+ }), cb);
167
+ },
168
+ setUid: function (uid, cb) { return withCallback(invokeNative('setOtaUid', { uid: uid || '' }), cb); },
169
+ setChannel: function (channel, cb) { return withCallback(invokeNative('setOtaChannel', { channel: channel || '' }), cb); },
170
+ downloadAndInstallApk: function (url, cb) {
171
+ return withCallback(invokeNative('downloadAndInstallApk', { url: url }), cb);
172
+ }
173
+ };
174
+
175
+ var Browser = {
176
+ open: function (urlOrOpts, cb) {
177
+ var opts = typeof urlOrOpts === 'string' ? { url: urlOrOpts } : (urlOrOpts || {});
178
+ if (!opts.url && opts.uri) opts.url = opts.uri;
179
+ return withCallback(invokeNative('openInBrowser', { url: opts.url || '', uri: opts.uri }), cb);
180
+ }
181
+ };
182
+
183
+ var Location = {
184
+ getStatus: function (cb) { return withCallback(invokeNative('getLocationStatus'), cb); },
185
+ requestPermission: function (cb) { return withCallback(invokeNative('requestLocationPermission'), cb); },
186
+ getCurrent: function (opts, cb) { return withCallback(invokeNative('getCurrentLocation', opts || {}), cb); },
187
+ startWatch: function (opts, cb) { return withCallback(invokeNative('startLocationWatch', opts || {}), cb); },
188
+ stopWatch: function (watchId, cb) { return withCallback(invokeNative('stopLocationWatch', { watchId: watchId }), cb); }
189
+ };
190
+
191
+ var Media = {
192
+ getVideoPlayerStatus: function (cb) { return withCallback(invokeNative('getVideoPlayerStatus'), cb); },
193
+ playVideo: function (opts, cb) { return withCallback(invokeNative('playVideo', opts), cb); }
194
+ };
195
+
196
+ var Http = {
197
+ request: function (opts, cb) { return withCallback(invokeNative('httpRequest', opts || {}), cb); }
198
+ };
199
+
200
+ var Clipboard = {
201
+ get: function (cb) { return withCallback(invokeNative('clipboardGet'), cb); },
202
+ set: function (text, cb) { return withCallback(invokeNative('clipboardSet', { text: text || '' }), cb); }
203
+ };
204
+ var Share = {
205
+ open: function (opts, cb) { return withCallback(invokeNative('share', opts || {}), cb); }
206
+ };
207
+ var Picker = {
208
+ chooseImage: function (cb) { return withCallback(invokeNative('pickImage'), cb); },
209
+ chooseVideo: function (cb) { return withCallback(invokeNative('pickVideo'), cb); },
210
+ chooseFile: function (cb) { return withCallback(invokeNative('pickFile'), cb); },
211
+ takePhoto: function (cb) { return withCallback(invokeNative('takePhoto'), cb); },
212
+ saveImage: function (opts, cb) { return withCallback(invokeNative('saveImage', opts || {}), cb); }
213
+ };
214
+ var Scan = {
215
+ scan: function (cb) { return withCallback(invokeNative('scanCode'), cb); }
216
+ };
217
+ var Biometric = {
218
+ status: function (cb) { return withCallback(invokeNative('biometricStatus'), cb); },
219
+ authenticate: function (opts, cb) { return withCallback(invokeNative('biometricAuth', opts || {}), cb); }
220
+ };
221
+ var Contacts = {
222
+ pick: function (cb) { return withCallback(invokeNative('pickContact'), cb); }
223
+ };
224
+ var Calendar = {
225
+ addEvent: function (opts, cb) { return withCallback(invokeNative('addCalendarEvent', opts || {}), cb); }
226
+ };
227
+ var Bluetooth = {
228
+ getState: function (cb) { return withCallback(invokeNative('bluetoothState'), cb); }
229
+ };
230
+ var Nfc = {
231
+ getState: function (cb) { return withCallback(invokeNative('nfcState'), cb); }
232
+ };
233
+ var Sensor = {
234
+ getMotion: function (cb) { return withCallback(invokeNative('sensorMotion'), cb); },
235
+ getPedometer: function (cb) { return withCallback(invokeNative('pedometer'), cb); }
236
+ };
237
+ var Haptics = {
238
+ vibrate: function (ms, cb) { return withCallback(invokeNative('vibrate', { ms: ms == null ? 200 : ms }), cb); }
239
+ };
240
+ var Flashlight = {
241
+ get: function (cb) { return withCallback(invokeNative('flashlightGet'), cb); },
242
+ set: function (on, cb) { return withCallback(invokeNative('flashlightSet', { on: !!on }), cb); }
243
+ };
244
+ var Brightness = {
245
+ get: function (cb) { return withCallback(invokeNative('brightnessGet'), cb); },
246
+ set: function (value, cb) { return withCallback(invokeNative('brightnessSet', { value: value }), cb); }
247
+ };
248
+ var Volume = {
249
+ get: function (cb) { return withCallback(invokeNative('volumeGet'), cb); },
250
+ set: function (value, cb) { return withCallback(invokeNative('volumeSet', { value: value }), cb); }
251
+ };
252
+ var Recorder = {
253
+ start: function (cb) { return withCallback(invokeNative('recorderStart'), cb); },
254
+ stop: function (cb) { return withCallback(invokeNative('recorderStop'), cb); }
255
+ };
256
+ var Capture = {
257
+ screenshot: function (cb) { return withCallback(invokeNative('screenshot'), cb); },
258
+ startScreenRecord: function (cb) { return withCallback(invokeNative('screenRecordStart'), cb); },
259
+ stopScreenRecord: function (cb) { return withCallback(invokeNative('screenRecordStop'), cb); }
260
+ };
261
+ var Payment = {
262
+ pay: function (opts, cb) { return withCallback(invokeNative('paymentPay', opts || {}), cb); }
263
+ };
264
+ var Store = {
265
+ requestReview: function (cb) { return withCallback(invokeNative('storeReview'), cb); }
266
+ };
267
+ var Push = {
268
+ getToken: function (cb) { return withCallback(invokeNative('pushToken'), cb); }
269
+ };
270
+
271
+ function pemToArrayBuffer(pem) {
272
+ var normalized = String(pem || '')
273
+ .replace(/-----BEGIN PUBLIC KEY-----/g, '')
274
+ .replace(/-----END PUBLIC KEY-----/g, '')
275
+ .replace(/\s+/g, '');
276
+ var binary = atob(normalized);
277
+ var bytes = new Uint8Array(binary.length);
278
+ for (var i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
279
+ return bytes.buffer;
280
+ }
281
+
282
+ function toBase64(buf) {
283
+ var view = buf instanceof Uint8Array ? buf : new Uint8Array(buf);
284
+ var binary = '';
285
+ for (var i = 0; i < view.length; i++) binary += String.fromCharCode(view[i]);
286
+ return btoa(binary);
287
+ }
288
+
289
+ function encryptRequestBody(plain, publicKeyPem, platformCode) {
290
+ var code = String(platformCode || (plain && plain.platformCode) || '').trim();
291
+ var pem = String(publicKeyPem || '').trim();
292
+ if (!code) return Promise.reject(new Error('[ota-native-bridge] platformCode is required for encryption'));
293
+ if (!pem) return Promise.reject(new Error('[ota-native-bridge] paramPublicKey is required for encryption'));
294
+ var subtle = global.crypto && global.crypto.subtle;
295
+ if (!subtle) return Promise.reject(new Error('[ota-native-bridge] Web Crypto API unavailable'));
296
+
297
+ return subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt']).then(function (aesKey) {
298
+ var iv = new Uint8Array(12);
299
+ global.crypto.getRandomValues(iv);
300
+ var plainBytes = new TextEncoder().encode(JSON.stringify(plain));
301
+ return subtle.encrypt({ name: 'AES-GCM', iv: iv, tagLength: 128 }, aesKey, plainBytes).then(function (cipherBuf) {
302
+ return subtle.exportKey('raw', aesKey).then(function (rawAes) {
303
+ return subtle.importKey(
304
+ 'spki',
305
+ pemToArrayBuffer(pem),
306
+ { name: 'RSA-OAEP', hash: 'SHA-256' },
307
+ false,
308
+ ['encrypt']
309
+ ).then(function (rsaKey) {
310
+ return subtle.encrypt({ name: 'RSA-OAEP' }, rsaKey, new Uint8Array(rawAes)).then(function (wrapped) {
311
+ return {
312
+ v: 1,
313
+ platformCode: code,
314
+ ek: toBase64(wrapped),
315
+ iv: toBase64(iv),
316
+ ct: toBase64(cipherBuf)
317
+ };
318
+ });
319
+ });
320
+ });
321
+ });
322
+ });
323
+ }
324
+
325
+ function postEncrypted(url, plain, publicKeyPem, init) {
326
+ init = init || {};
327
+ return encryptRequestBody(plain, publicKeyPem).then(function (envelope) {
328
+ var headers = Object.assign({ 'Content-Type': 'application/json' }, init.headers || {});
329
+ return fetch(url, Object.assign({}, init, {
330
+ method: 'POST',
331
+ headers: headers,
332
+ body: JSON.stringify(envelope)
333
+ })).then(function (response) {
334
+ return response.text().then(function (text) {
335
+ try {
336
+ return text ? JSON.parse(text) : { code: response.status };
337
+ } catch (e) {
338
+ return { code: response.status, message: text };
339
+ }
340
+ });
341
+ });
342
+ });
343
+ }
344
+
345
+ var Crypto = {
346
+ encryptRequestBody: encryptRequestBody,
347
+ postEncrypted: postEncrypted
348
+ };
349
+
350
+ var plugins = {
351
+ App: App, Ota: Ota, Browser: Browser, Device: Device, Config: Config, Theme: Theme, Icon: Icon,
352
+ Viewport: Viewport, Notification: Notification, Location: Location, Media: Media, Http: Http,
353
+ Clipboard: Clipboard, Share: Share, Picker: Picker, Scan: Scan, Biometric: Biometric,
354
+ Contacts: Contacts, Calendar: Calendar, Bluetooth: Bluetooth, Nfc: Nfc, Sensor: Sensor,
355
+ Haptics: Haptics, Flashlight: Flashlight, Brightness: Brightness, Volume: Volume,
356
+ Recorder: Recorder, Capture: Capture, Payment: Payment, Store: Store, Push: Push
357
+ };
358
+
359
+ global.Native = {
360
+ sdkVersion: '1.2.0',
361
+ getPlatform: getPlatform,
362
+ isNativePlatform: isNativePlatform,
363
+ isNativeBridgeAvailable: function () { return !!getNativeMessenger(); },
364
+ whenReady: waitForBridge,
365
+ Plugins: plugins,
366
+ App: App,
367
+ Ota: Ota,
368
+ Browser: Browser,
369
+ Device: Device,
370
+ Config: Config,
371
+ Theme: Theme,
372
+ Icon: Icon,
373
+ Viewport: Viewport,
374
+ Notification: Notification,
375
+ Location: Location,
376
+ Media: Media,
377
+ Http: Http,
378
+ Clipboard: Clipboard,
379
+ Share: Share,
380
+ Picker: Picker,
381
+ Scan: Scan,
382
+ Biometric: Biometric,
383
+ Contacts: Contacts,
384
+ Calendar: Calendar,
385
+ Bluetooth: Bluetooth,
386
+ Nfc: Nfc,
387
+ Sensor: Sensor,
388
+ Haptics: Haptics,
389
+ Flashlight: Flashlight,
390
+ Brightness: Brightness,
391
+ Volume: Volume,
392
+ Recorder: Recorder,
393
+ Capture: Capture,
394
+ Payment: Payment,
395
+ Store: Store,
396
+ Push: Push,
397
+ Crypto: Crypto
398
+ };
399
+ })(typeof window !== 'undefined' ? window : globalThis);
package/package.json ADDED
@@ -0,0 +1,75 @@
1
+ {
2
+ "name": "ota-native-bridge",
3
+ "version": "1.2.0",
4
+ "description": "App OTA WebView 壳应用跨平台 Native Bridge TypeScript SDK(Android / iOS / HarmonyOS)",
5
+ "keywords": [
6
+ "ota",
7
+ "webview",
8
+ "bridge",
9
+ "openharmony",
10
+ "android",
11
+ "ios"
12
+ ],
13
+ "license": "MIT",
14
+ "author": "",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": ""
18
+ },
19
+ "type": "module",
20
+ "main": "./dist/cjs/index.js",
21
+ "module": "./dist/index.js",
22
+ "types": "./dist/index.d.ts",
23
+ "typings": "./dist/index.d.ts",
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/index.d.ts",
27
+ "import": "./dist/index.js",
28
+ "require": "./dist/cjs/index.js",
29
+ "default": "./dist/index.js"
30
+ },
31
+ "./ota-native-bridge": {
32
+ "types": "./ota-native-bridge.d.ts",
33
+ "default": "./ota-native-bridge.js"
34
+ },
35
+ "./package.json": "./package.json"
36
+ },
37
+ "typesVersions": {
38
+ "*": {
39
+ "*": [
40
+ "./dist/index.d.ts"
41
+ ]
42
+ }
43
+ },
44
+ "sideEffects": [
45
+ "./ota-native-bridge.js"
46
+ ],
47
+ "files": [
48
+ "dist",
49
+ "ota-native-bridge.js",
50
+ "ota-native-bridge.d.ts",
51
+ "README.md",
52
+ "docs/USAGE.md"
53
+ ],
54
+ "scripts": {
55
+ "build": "npm run clean && npm run build:types && npm run build:cjs && npm run verify:types",
56
+ "build:types": "tsc -p tsconfig.json",
57
+ "build:esm": "npm run build:types",
58
+ "build:cjs": "tsc -p tsconfig.cjs.json",
59
+ "verify:types": "node scripts/verify-dts.mjs",
60
+ "clean": "rm -rf dist",
61
+ "sync:bridge": "node scripts/sync-ota-native-bridge.mjs",
62
+ "prepublishOnly": "npm run build",
63
+ "prepare": "npm run build"
64
+ },
65
+ "devDependencies": {
66
+ "typescript": "^5.7.2"
67
+ },
68
+ "engines": {
69
+ "node": ">=18"
70
+ },
71
+ "publishConfig": {
72
+ "access": "public",
73
+ "registry": "https://registry.npmjs.org/"
74
+ }
75
+ }