1
0
mirror of https://gitcode.com/gh_mirrors/re/react-native-pushy.git synced 2025-09-17 17:56:11 +08:00
Code Issues Packages Projects Releases Wiki Activity GitHub Gitee

Compare commits

..

11 Commits

Author SHA1 Message Date
sunnylqm
23d1fcd4d1 Bump package version to 10.25.1 2025-02-26 12:50:18 +08:00
sunnylqm
e3a748065a Fix linking event listener removal for legacy compatibility 2025-02-26 12:48:26 +08:00
sunnylqm
effd7e129d fix android reload in bridge-less mode 2025-02-25 23:22:31 +08:00
sunnylqm
9a00cf7483 Bump package version to 10.24.3 2025-02-25 19:33:43 +08:00
sunnylqm
d854082495 Clear hash info on package version update 2025-02-25 19:33:02 +08:00
sunnylqm
3073bd99db update example 2025-02-23 17:43:24 +08:00
sunnylqm
4436654769 fix class properties 2025-02-23 17:26:59 +08:00
sunnylqm
3ccc3653ac export useUpdate 2025-02-22 11:20:43 +08:00
sunnylqm
e150db486a add cresc 2025-02-21 18:41:39 +08:00
sunnylqm
66c2504718 comments 2025-02-18 22:38:09 +08:00
sunnylqm
bbda7217ac add cresc 2025-02-18 15:16:01 +08:00
15 changed files with 486 additions and 444 deletions

View File

@@ -12,7 +12,7 @@
"react-native-paper": "^5.13.1",
"react-native-safe-area-context": "^5.2.0",
"react-native-svg": "^15.11.1",
"react-native-update": "^10.23.0",
"react-native-update": "^10.25.0",
"react-native-vector-icons": "^10.2.0",
},
"devDependencies": {
@@ -1434,7 +1434,7 @@
"react-native-svg": ["react-native-svg@15.11.1", "", { "dependencies": { "css-select": "^5.1.0", "css-tree": "^1.1.3", "warn-once": "0.1.1" }, "peerDependencies": { "react": "*", "react-native": "*" } }, "sha512-Qmwx/yJKt+AHUr4zjxx/Q69qwKtRfr1+uIfFMQoq3WFRhqU76aL9db1DyvPiY632DAsVGba1pHf92OZPkpjrdQ=="],
"react-native-update": ["react-native-update@10.23.0", "", { "dependencies": { "nanoid": "^3.3.3", "react-native-url-polyfill": "^2.0.0" }, "peerDependencies": { "react": ">=16.8.0", "react-native": ">=0.59.0" } }, "sha512-gt6kL5Fd8iG46YYwvcuiD6Yod7DSzNZ/Qo5YuiAXrdO/h+3SCJsfDGVmSpanShwAepvvuAUELIJZIRpSrJdIvA=="],
"react-native-update": ["react-native-update@10.25.0", "", { "dependencies": { "nanoid": "^3.3.3", "react-native-url-polyfill": "^2.0.0" }, "peerDependencies": { "react": ">=16.8.0", "react-native": ">=0.59.0" } }, "sha512-4EYcYZFMhd/VMk9EwND4N2NOBZJYTksvbLdGTgqwYA1NT4IUmBgTFGeeng8GzazOqh4yP0tlW98zpW+67DEZsg=="],
"react-native-url-polyfill": ["react-native-url-polyfill@2.0.0", "", { "dependencies": { "whatwg-url-without-unicode": "8.0.0-3" }, "peerDependencies": { "react-native": "*" } }, "sha512-My330Do7/DvKnEvwQc0WdcBnFPploYKp9CYlefDXzIdEaA+PAhDYllkvGeEroEzvc4Kzzj2O4yVdz8v6fjRvhA=="],

File diff suppressed because it is too large Load Diff

View File

@@ -23,7 +23,7 @@
"react-native-paper": "^5.13.1",
"react-native-safe-area-context": "^5.2.0",
"react-native-svg": "^15.11.1",
"react-native-update": "^10.23.0",
"react-native-update": "^10.25.0",
"react-native-vector-icons": "^10.2.0"
},
"devDependencies": {

View File

@@ -25,7 +25,7 @@ import {LocalSvg} from 'react-native-svg/css';
import TestConsole from './TestConsole';
import _updateConfig from '../update.json';
import {PushyProvider, Pushy, usePushy} from 'react-native-update';
import {UpdateProvider, Pushy, Cresc, useUpdate} from 'react-native-update';
const {appKey} = _updateConfig[Platform.OS];
function App() {
@@ -40,7 +40,7 @@ function App() {
currentHash,
parseTestQrCode,
progress: {received, total} = {},
} = usePushy();
} = useUpdate();
const [useDefaultAlert, setUseDefaultAlert] = useState(true);
const [showTestConsole, setShowTestConsole] = useState(false);
const [showUpdateBanner, setShowUpdateBanner] = useState(false);
@@ -203,17 +203,24 @@ const styles = StyleSheet.create({
image: {},
});
const pushyClient = new Pushy({
// use Pushy for China users
// const updateClient = new Pushy({
// appKey,
// debug: true,
// });
// use Cresc for global users
const updateClient = new Cresc({
appKey,
debug: true,
});
export default function Root() {
return (
<PushyProvider client={pushyClient}>
<UpdateProvider client={updateClient}>
<PaperProvider>
<App />
</PaperProvider>
</PushyProvider>
</UpdateProvider>
);
}

View File

@@ -98,23 +98,20 @@ public class UpdateModuleImpl {
}
});
}catch (Exception e){
promise.reject("执行报错:" + e.getMessage());
promise.reject("downloadPatchFromPpk failed: "+e.getMessage());
}
}
public static void reloadUpdate(UpdateContext updateContext, ReactApplicationContext mContext, ReadableMap options, Promise promise) {
final String hash = options.getString("hash");
if (hash == null || hash.isEmpty()) {
promise.reject("hash不能为空");
return;
}
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
updateContext.switchVersion(hash);
final Context application = mContext.getApplicationContext();
JSBundleLoader loader = JSBundleLoader.createFileLoader(UpdateContext.getBundleUrl(application));
try {
updateContext.switchVersion(hash);
final Context application = mContext.getApplicationContext();
ReactInstanceManager instanceManager = updateContext.getCustomReactInstanceManager();
if (instanceManager == null) {
@@ -122,12 +119,10 @@ public class UpdateModuleImpl {
}
try {
JSBundleLoader loader = JSBundleLoader.createFileLoader(UpdateContext.getBundleUrl(application));
Field loadField = instanceManager.getClass().getDeclaredField("mBundleLoader");
loadField.setAccessible(true);
loadField.set(instanceManager, loader);
} catch (Throwable err) {
promise.reject("pushy:"+err.getMessage());
Field jsBundleField = instanceManager.getClass().getDeclaredField("mJSBundleFile");
jsBundleField.setAccessible(true);
jsBundleField.set(instanceManager, UpdateContext.getBundleUrl(application));
@@ -137,31 +132,36 @@ public class UpdateModuleImpl {
promise.resolve(true);
} catch (Throwable err) {
promise.reject(err);
Log.e("pushy", "switchVersion failed ", err);
final Activity currentActivity = mContext.getCurrentActivity();
if (currentActivity == null) {
return;
}
try {
// Try to get getReactDelegate method using reflection
java.lang.reflect.Method getReactDelegateMethod =
ReactActivity.class.getMethod("getReactDelegate");
if (getReactDelegateMethod != null) {
ReactDelegate reactDelegate = (ReactDelegate)
getReactDelegateMethod.invoke(currentActivity);
// Try to get reload method using reflection
java.lang.reflect.Method reloadMethod =
ReactDelegate.class.getMethod("reload");
if (reloadMethod != null) {
reloadMethod.invoke(reactDelegate);
} else {
throw new NoSuchMethodException();
}
} else {
throw new NoSuchMethodException();
}
ReactDelegate reactDelegate = (ReactDelegate)
getReactDelegateMethod.invoke(currentActivity);
Field reactHostField = ReactDelegate.class.getDeclaredField("mReactHost");
reactHostField.setAccessible(true);
Object reactHost = reactHostField.get(reactDelegate);
// Access the mReactHostDelegate field
Field reactHostDelegateField = reactHost.getClass().getDeclaredField("mReactHostDelegate");
reactHostDelegateField.setAccessible(true);
Object reactHostDelegate = reactHostDelegateField.get(reactHost);
// Modify the jsBundleLoader field
Field jsBundleLoaderField = reactHostDelegate.getClass().getDeclaredField("jsBundleLoader");
jsBundleLoaderField.setAccessible(true);
jsBundleLoaderField.set(reactHostDelegate, loader);
// Get the reload method with a String parameter
java.lang.reflect.Method reloadMethod = reactHost.getClass().getMethod("reload", String.class);
// Invoke the reload method with a reason
reloadMethod.invoke(reactHost, "react-native-update");
} catch (Throwable e) {
currentActivity.runOnUiThread(new Runnable() {
@Override
@@ -171,72 +171,54 @@ public class UpdateModuleImpl {
});
}
}
promise.resolve(true);
}
});
}
public static void setNeedUpdate(UpdateContext updateContext, ReadableMap options,Promise promise) {
try {
final String hash = options.getString("hash");
if(hash==null || hash.isEmpty()){
promise.reject("hash不能为空");
return;
}
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
updateContext.switchVersion(hash);
promise.resolve(true);
} catch (Throwable err) {
promise.reject("switchVersionLater failed:"+err.getMessage());
Log.e("pushy", "switchVersionLater failed", err);
}
public static void setNeedUpdate(UpdateContext updateContext, ReadableMap options, Promise promise) {
final String hash = options.getString("hash");
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
updateContext.switchVersion(hash);
promise.resolve(true);
} catch (Throwable err) {
promise.reject("switchVersionLater failed: "+err.getMessage());
Log.e("pushy", "switchVersionLater failed", err);
}
});
} catch (Exception e){
promise.reject("执行报错:"+e.getMessage());
}
}
});
}
public static void markSuccess(UpdateContext updateContext,Promise promise) {
try {
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
updateContext.markSuccess();
promise.resolve(true);
}
});
} catch (Exception e){
promise.reject("执行报错:"+e.getMessage());
}
public static void markSuccess(UpdateContext updateContext, Promise promise) {
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
updateContext.markSuccess();
promise.resolve(true);
}
});
}
public static void setUuid(UpdateContext updateContext, String uuid, Promise promise) {
try {
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
updateContext.setKv("uuid", uuid);
promise.resolve(true);
}
});
} catch (Exception e){
promise.reject("执行报错:"+e.getMessage());
}
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
updateContext.setKv("uuid", uuid);
promise.resolve(true);
}
});
}
public static boolean check(String json) {
ObjectMapper mapper = new ObjectMapper();
try {
mapper.readValue(json, Map.class);
System.out.println("String can be converted to Map");
return true;
} catch (IOException e) {
System.out.println("String cannot be converted to Map");
return false;
}
}
@@ -246,12 +228,12 @@ public class UpdateModuleImpl {
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
if(!check(info)){
updateContext.setKv("hash_" + hash, info);
promise.reject("校验报错:json字符串格式错误");
}else {
if (check(info)) {
updateContext.setKv("hash_" + hash, info);
promise.resolve(true);
} else {
updateContext.setKv("hash_" + hash, info);
promise.reject("setLocalHashInfo failed: invalid json string");
}
}
});
@@ -262,7 +244,7 @@ public class UpdateModuleImpl {
if (check(value)) {
promise.resolve(value);
} else {
promise.reject("校验报错:json字符串格式错误");
promise.reject("getLocalHashInfo failed: invalid json string");
}
}

1
endpoints_cresc.json Normal file
View File

@@ -0,0 +1 @@
["https://cresc-server-pthxtmvcnf.ap-southeast-1.fcapp.run"]

View File

@@ -78,6 +78,7 @@ RCT_EXPORT_MODULE(RCTPushy);
BOOL needClearPushyInfo = ![curPackageVersion isEqualToString:packageVersion];
if (needClearPushyInfo) {
[defaults setObject:nil forKey:keyPushyInfo];
[defaults setObject:nil forKey:keyHashInfo];
[defaults setObject:@(YES) forKey:KeyPackageUpdatedMarked];
// ...need clear files later

View File

@@ -1,6 +1,6 @@
{
"name": "react-native-update",
"version": "10.23.1",
"version": "10.25.1",
"description": "react-native hot update",
"main": "src/index",
"scripts": {
@@ -74,6 +74,5 @@
"react-native": "0.73",
"ts-jest": "^29.2.5",
"typescript": "^5.6.3"
},
"packageManager": "yarn@1.22.21+sha1.1959a18351b811cdeedbd484a8f86c3cc3bbaf72"
}
}

View File

@@ -1,5 +1,14 @@
import { CheckResult, PushyOptions, ProgressData, EventType } from './type';
import { emptyObj, joinUrls, log, noop, promiseAny, testUrls } from './utils';
import { CheckResult, ClientOptions, ProgressData, EventType } from './type';
import {
assertDev,
assertWeb,
emptyObj,
joinUrls,
log,
noop,
promiseAny,
testUrls,
} from './utils';
import { EmitterSubscription, Platform } from 'react-native';
import { PermissionsAndroid } from './permissions';
import {
@@ -15,31 +24,42 @@ import {
isRolledBack,
} from './core';
const defaultServer = {
main: 'https://update.react-native.cn/api',
backups: ['https://update.reactnative.cn/api'],
queryUrls: [
'https://gitee.com/sunnylqm/react-native-pushy/raw/master/endpoints.json',
'https://cdn.jsdelivr.net/gh/reactnativecn/react-native-update@master/endpoints.json',
],
const SERVER_PRESETS = {
// cn
Pushy: {
main: 'https://update.react-native.cn/api',
backups: ['https://update.reactnative.cn/api'],
queryUrls: [
'https://gitee.com/sunnylqm/react-native-pushy/raw/master/endpoints.json',
'https://cdn.jsdelivr.net/gh/reactnativecn/react-native-update@master/endpoints.json',
],
},
// i18n
Cresc: {
main: 'https://api.cresc.dev',
backups: ['https://api.cresc.app'],
queryUrls: [
'https://cdn.jsdelivr.net/gh/reactnativecn/react-native-update@master/endpoints_cresc.json',
],
},
};
if (Platform.OS === 'web') {
console.warn('react-native-update 不支持 web 端热更,不会执行操作');
}
assertWeb();
const defaultClientOptions: ClientOptions = {
appKey: '',
autoMarkSuccess: true,
updateStrategy: __DEV__ ? 'alwaysAlert' : 'alertUpdateAndIgnoreError',
checkStrategy: 'both',
logger: noop,
debug: false,
throwError: false,
};
// for China users
export class Pushy {
options: PushyOptions = {
appKey: '',
server: defaultServer,
autoMarkSuccess: true,
updateStrategy: __DEV__ ? 'alwaysAlert' : 'alertUpdateAndIgnoreError',
checkStrategy: 'both',
logger: noop,
debug: false,
throwError: false,
};
options = defaultClientOptions;
clientType: 'Pushy' | 'Cresc' = 'Pushy';
lastChecking?: number;
lastRespJson?: Promise<any>;
@@ -50,7 +70,7 @@ export class Pushy {
static marked = false;
static applyingUpdate = false;
version = cInfo.pushy;
version = cInfo.rnu;
loggerPromise = (() => {
let resolve: (value?: unknown) => void = () => {};
const promise = new Promise(res => {
@@ -62,12 +82,14 @@ export class Pushy {
};
})();
constructor(options: PushyOptions) {
constructor(options: ClientOptions) {
if (Platform.OS === 'ios' || Platform.OS === 'android') {
if (!options.appKey) {
throw new Error('appKey is required');
}
}
this.clientType = new.target.name as 'Pushy' | 'Cresc';
this.options.server = SERVER_PRESETS[this.clientType];
this.setOptions(options);
if (isRolledBack) {
this.report({
@@ -79,7 +101,7 @@ export class Pushy {
}
}
setOptions = (options: Partial<PushyOptions>) => {
setOptions = (options: Partial<ClientOptions>) => {
for (const [key, value] of Object.entries(options)) {
if (value !== undefined) {
(this.options as any)[key] = value;
@@ -124,15 +146,24 @@ export class Pushy {
return `${endpoint}/checkUpdate/${this.options.appKey}`;
};
static assertHash = (hash: string) => {
if (!Pushy.downloadedHash) {
if (!this.downloadedHash) {
return;
}
if (hash !== Pushy.downloadedHash) {
if (hash !== this.downloadedHash) {
log(`use downloaded hash ${Pushy.downloadedHash} first`);
return;
}
return true;
};
assertDebug = () => {
if (__DEV__ && !this.options.debug) {
console.info(
'You are currently in the development environment and have not enabled debug mode. The hot update check will not be performed. If you need to debug hot updates in the development environment, please set debug to true in the client.',
);
return false;
}
return true;
};
markSuccess = () => {
if (Pushy.marked || __DEV__ || !isFirstTime) {
return;
@@ -142,10 +173,7 @@ export class Pushy {
this.report({ type: 'markSuccess' });
};
switchVersion = async (hash: string) => {
if (__DEV__) {
console.warn(
'您调用了switchVersion方法但是当前是开发环境不会进行任何操作。',
);
if (!assertDev('switchVersion()')) {
return;
}
if (Pushy.assertHash(hash) && !Pushy.applyingUpdate) {
@@ -156,10 +184,7 @@ export class Pushy {
};
switchVersionLater = async (hash: string) => {
if (__DEV__) {
console.warn(
'您调用了switchVersionLater方法但是当前是开发环境不会进行任何操作。',
);
if (!assertDev('switchVersionLater()')) {
return;
}
if (Pushy.assertHash(hash)) {
@@ -168,21 +193,17 @@ export class Pushy {
}
};
checkUpdate = async (extra?: Record<string, any>) => {
if (__DEV__ && !this.options.debug) {
console.info(
'您当前处于开发环境且未启用 debug不会进行热更检查。如需在开发环境中调试热更请在 client 中设置 debug 为 true',
);
if (!this.assertDebug()) {
return;
}
if (Platform.OS === 'web') {
console.warn('web 端不支持热更新检查');
if (!assertWeb()) {
return;
}
if (
this.options.beforeCheckUpdate &&
(await this.options.beforeCheckUpdate()) === false
) {
log('beforeCheckUpdate 返回 false, 忽略检查');
log('beforeCheckUpdate returned false, skipping check');
return;
}
const now = Date.now();
@@ -310,7 +331,7 @@ export class Pushy {
this.options.beforeDownloadUpdate &&
(await this.options.beforeDownloadUpdate(info)) === false
) {
log('beforeDownloadUpdate 返回 false, 忽略下载');
log('beforeDownloadUpdate returned false, skipping download');
return;
}
if (!info.update || !hash) {
@@ -489,3 +510,6 @@ export class Pushy {
}
};
}
// for international users
export class Cresc extends Pushy {}

View File

@@ -1,6 +1,6 @@
import { createContext, useContext } from 'react';
import { CheckResult, ProgressData } from './type';
import { Pushy } from './client';
import { Pushy, Cresc } from './client';
const noop = () => {};
const asyncNoop = () => Promise.resolve();
@@ -19,7 +19,7 @@ export const defaultContext = {
packageVersion: '',
};
export const PushyContext = createContext<{
export const UpdateContext = createContext<{
checkUpdate: () => Promise<void>;
switchVersion: () => Promise<void>;
switchVersionLater: () => Promise<void>;
@@ -35,10 +35,14 @@ export const PushyContext = createContext<{
parseTestQrCode: (code: string) => boolean;
currentHash: string;
packageVersion: string;
client?: Pushy;
client?: Pushy | Cresc;
progress?: ProgressData;
updateInfo?: CheckResult;
lastError?: Error;
}>(defaultContext);
export const usePushy = () => useContext(PushyContext);
export const useUpdate = () => useContext(UpdateContext);
export const usePushy = useUpdate;
export const useCresc = useUpdate;

View File

@@ -13,8 +13,12 @@ export const PushyModule =
? require('./NativePushy').default
: NativeModules.Pushy;
export const UpdateModule = PushyModule;
if (!PushyModule) {
throw new Error('react-native-update 模块无法加载,请尝试重新编译');
throw new Error(
'Failed to load react-native-update native module, please try to recompile',
);
}
const PushyConstants = isTurboModuleEnabled
@@ -31,12 +35,6 @@ export const isRolledBack: boolean = typeof rolledBackVersion === 'string';
export const buildTime: string = PushyConstants.buildTime;
let uuid = PushyConstants.uuid;
if (Platform.OS === 'android' && !PushyConstants.isUsingBundleUrl) {
console.warn(
'react-native-update 没有检测到 Bundle URL 的配置,这可能是因为您使用了某种懒加载机制(比如使用 expo可忽略本警告或是 Bundle URL 的配置不正确(请对照文档检查)',
);
}
export function setLocalHashInfo(hash: string, info: Record<string, any>) {
PushyModule.setLocalHashInfo(hash, JSON.stringify(info));
}
@@ -63,7 +61,7 @@ if (!uuid) {
log('uuid: ' + uuid);
export const cInfo = {
pushy: require('../package.json').version,
rnu: require('../package.json').version,
rn: RNVersion,
os: Platform.OS + ' ' + Platform.Version,
uuid,

View File

@@ -1,4 +1,4 @@
export { Pushy } from './client';
export { PushyContext, usePushy } from './context';
export { PushyProvider } from './provider';
export { PushyModule } from './core';
export { Pushy, Cresc } from './client';
export { UpdateContext, usePushy, useCresc, useUpdate } from './context';
export { PushyProvider, UpdateProvider } from './provider';
export { PushyModule, UpdateModule } from './core';

View File

@@ -12,22 +12,24 @@ import {
Platform,
Linking,
} from 'react-native';
import { Pushy } from './client';
import { Pushy, Cresc } from './client';
import { currentVersion, packageVersion, getCurrentVersionInfo } from './core';
import { CheckResult, ProgressData, PushyTestPayload } from './type';
import { PushyContext } from './context';
import { CheckResult, ProgressData, UpdateTestPayload } from './type';
import { UpdateContext } from './context';
import { URL } from 'react-native-url-polyfill';
import { isInRollout } from './isInRollout';
import { log } from './utils';
export const PushyProvider = ({
export const UpdateProvider = ({
client,
children,
}: {
client: Pushy;
client: Pushy | Cresc;
children: ReactNode;
}) => {
client = useRef(client).current;
const { options } = client;
const stateListener = useRef<NativeEventSubscription>();
const [updateInfo, setUpdateInfo] = useState<CheckResult>();
const updateInfoRef = useRef(updateInfo);
@@ -239,10 +241,7 @@ export const PushyProvider = ({
const markSuccess = client.markSuccess;
useEffect(() => {
if (__DEV__ && !options.debug) {
console.info(
'您当前处于开发环境且未启用debug不会进行热更检查。如需在开发环境中调试热更请在client中设置debug为true',
);
if (!client.assertDebug()) {
return;
}
const { checkStrategy, dismissErrorAfter, autoMarkSuccess } = options;
@@ -272,11 +271,11 @@ export const PushyProvider = ({
stateListener.current && stateListener.current.remove();
clearTimeout(dismissErrorTimer);
};
}, [checkUpdate, options, dismissError, markSuccess]);
}, [checkUpdate, options, dismissError, markSuccess, client]);
const parseTestPayload = useCallback(
(payload: PushyTestPayload) => {
if (payload && payload.type && payload.type.startsWith('__rnPushy')) {
(payload: UpdateTestPayload) => {
if (payload && payload.type && payload.type.startsWith('__rnUpdate')) {
const logger = options.logger || (() => {});
options.logger = ({ type, data }) => {
logger({ type, data });
@@ -286,8 +285,8 @@ export const PushyProvider = ({
checkUpdate({ extra: { toHash: payload.data } }).then(() => {
if (updateInfoRef.current && updateInfoRef.current.upToDate) {
Alert.alert(
'提示',
'当前尚未检测到更新版本如果是首次扫码请等待服务器端生成补丁包后再试约10秒',
'Info',
'No update found, please wait 10s for the server to generate the patch package',
);
}
options.logger = logger;
@@ -301,7 +300,7 @@ export const PushyProvider = ({
);
const parseTestQrCode = useCallback(
(code: string | PushyTestPayload) => {
(code: string | UpdateTestPayload) => {
try {
const payload = typeof code === 'string' ? JSON.parse(code) : code;
return parseTestPayload(payload);
@@ -326,16 +325,21 @@ export const PushyProvider = ({
};
Linking.getInitialURL().then(parseLinking);
const linkingListener = Linking.addEventListener('url', ({ url }) =>
parseLinking(url),
);
const linkingHandler = ({ url }: { url: string }) => {
parseLinking(url);
};
const linkingListener = Linking.addEventListener('url', linkingHandler);
return () => {
linkingListener.remove();
if (typeof linkingListener.remove === 'function') {
linkingListener.remove();
} else if ('removeEventListener' in Linking) {
(Linking as any).removeEventListener('url', linkingHandler);
}
};
}, [parseTestPayload]);
return (
<PushyContext.Provider
<UpdateContext.Provider
value={{
checkUpdate,
switchVersion,
@@ -354,6 +358,8 @@ export const PushyProvider = ({
parseTestQrCode,
}}>
{children}
</PushyContext.Provider>
</UpdateContext.Provider>
);
};
export const PushyProvider = UpdateProvider;

View File

@@ -44,7 +44,7 @@ export type EventType =
export interface EventData {
currentVersion: string;
cInfo: {
pushy: string;
rnu: string;
rn: string;
os: string;
uuid: string;
@@ -65,15 +65,15 @@ export type UpdateEventsLogger = ({
data: EventData;
}) => void;
export interface PushyServerConfig {
export interface UpdateServerConfig {
main: string;
backups?: string[];
queryUrls?: string[];
}
export interface PushyOptions {
export interface ClientOptions {
appKey: string;
server?: PushyServerConfig;
server?: UpdateServerConfig;
logger?: UpdateEventsLogger;
updateStrategy?:
| 'alwaysAlert'
@@ -90,7 +90,7 @@ export interface PushyOptions {
beforeDownloadUpdate?: (info: CheckResult) => Promise<boolean>;
}
export interface PushyTestPayload {
export interface UpdateTestPayload {
type: '__rnPushyVersionHash' | string | null;
data: any;
}

View File

@@ -1,7 +1,7 @@
import { Platform } from 'react-native';
export function log(...args: any[]) {
console.log('pushy: ', ...args);
console.log('react-native-update: ', ...args);
}
export function promiseAny<T>(promises: Promise<T>[]) {
@@ -84,3 +84,23 @@ export const testUrls = async (urls?: string[]) => {
log('all ping failed, use first url:', urls[0]);
return urls[0];
};
export const assertWeb = () => {
if (Platform.OS === 'web') {
console.warn(
'react-native-update does not support the Web platform and will not perform any operations',
);
return false;
}
return true;
};
export const assertDev = (matter: string) => {
if (__DEV__) {
console.warn(
`${matter} is not supported in development environment; no action taken.`,
);
return false;
}
return true;
};