@webority/mobile-core 0.147.0 → 0.149.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.
- package/lib/commonjs/api/fetchRetry.js +1 -1
- package/lib/commonjs/api/retry.js +1 -1
- package/lib/commonjs/api/tokenRefresh.js +1 -1
- package/lib/commonjs/api/userClient.js +1 -1
- package/lib/commonjs/auth/authStore.js +1 -1
- package/lib/commonjs/download/adapters/expoFs.js +1 -1
- package/lib/commonjs/push/broadcasts.js +1 -1
- package/lib/commonjs/push/push.js +1 -1
- package/lib/commonjs/secureScreen/index.js +1 -1
- package/lib/commonjs/smsRetriever/index.js +1 -1
- package/lib/commonjs/updates/updates.js +1 -1
- package/lib/module/api/fetchRetry.js +1 -1
- package/lib/module/api/retry.js +1 -1
- package/lib/module/api/tokenRefresh.js +1 -1
- package/lib/module/api/userClient.js +1 -1
- package/lib/module/auth/authStore.js +1 -1
- package/lib/module/download/adapters/expoFs.js +1 -1
- package/lib/module/push/broadcasts.js +1 -1
- package/lib/module/push/push.js +1 -1
- package/lib/module/secureScreen/index.js +1 -1
- package/lib/module/smsRetriever/index.js +1 -1
- package/lib/module/updates/updates.js +1 -1
- package/lib/typescript/commonjs/api/fetchRetry.d.ts +5 -0
- package/lib/typescript/commonjs/api/retry.d.ts +13 -0
- package/lib/typescript/commonjs/api/tokenRefresh.d.ts +7 -1
- package/lib/typescript/commonjs/download/adapters/expoFs.d.ts +1 -1
- package/lib/typescript/commonjs/formatters/currency.d.ts +1 -0
- package/lib/typescript/commonjs/push/broadcasts.d.ts +3 -1
- package/lib/typescript/commonjs/push/push.d.ts +3 -0
- package/lib/typescript/commonjs/secureScreen/index.d.ts +4 -1
- package/lib/typescript/commonjs/smsRetriever/index.d.ts +1 -0
- package/lib/typescript/module/api/fetchRetry.d.ts +5 -0
- package/lib/typescript/module/api/retry.d.ts +13 -0
- package/lib/typescript/module/api/tokenRefresh.d.ts +7 -1
- package/lib/typescript/module/download/adapters/expoFs.d.ts +1 -1
- package/lib/typescript/module/formatters/currency.d.ts +1 -0
- package/lib/typescript/module/push/broadcasts.d.ts +3 -1
- package/lib/typescript/module/push/push.d.ts +3 -0
- package/lib/typescript/module/secureScreen/index.d.ts +4 -1
- package/lib/typescript/module/smsRetriever/index.d.ts +1 -0
- package/package.json +45 -45
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.fetchWithRetry=void 0;var _retry=require("./retry.js");const
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.fetchWithRetry=void 0;var _retry=require("./retry.js");const DEFAULT_RETRIES=3,defaultDelayMs=e=>Math.random()*Math.min(2e3,500*2**(e-1)),retryAfterFrom=e=>{const t=Number(e.headers.get("retry-after"));return Number.isFinite(t)&&t>0?1e3*t:null},hasIdempotencyKey=e=>{const t=new Headers(e.headers).get(_retry.IDEMPOTENCY_KEY_HEADER);return null!==t&&""!==t},fetchWithRetry=async(e,t,r,s={})=>{const a=s.retries??3,o=s.retryDelayMs??defaultDelayMs,i=r.signal??void 0,y=!0===s.sideEffectFree||(0,_retry.isIdempotentMethod)(r.method??"GET"),n=hasIdempotencyKey(r);for(let s=0;;s++){let h,d;try{h=await e(t,r)}catch(e){if(!(e instanceof TypeError))throw e;d=e}const c=h?retryAfterFrom(h):null;if(!(0,_retry.isRetryableRequest)({idempotent:y,status:h?.status,namedWaitMs:c,hasIdempotencyKey:n})||s>=a||i?.aborted){if(h)return h;throw d}if(!await(0,_retry.waitOrAbort)(c??o(s+1),i)){if(h)return h;throw d}}};exports.fetchWithRetry=fetchWithRetry;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.waitOrAbort=exports.retryAfterMs=exports.resendWhenUnanswered=exports.isRetryableStatus=exports.isRetryableFailure=exports.isNeverSentError=exports.attachRetry=exports.IDEMPOTENCY_KEY_HEADER=void 0;var _axios=_interopRequireDefault(require("axios")),_index=require("../config/index.js"),_workspace=require("./workspace.js");function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}const IDEMPOTENCY_KEY_HEADER=exports.IDEMPOTENCY_KEY_HEADER="Idempotency-Key",isRetryableStatus=e=>"number"==typeof e&&(429===e||e>=500&&e<=599);exports.isRetryableStatus=isRetryableStatus;const IDEMPOTENT_METHODS=new Set(["get","head","options","put","delete"]),NEVER_SENT_CODES=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN","ENETUNREACH","EHOSTUNREACH"]),isNeverSentError=e=>!e.response&&"string"==typeof e.code&&NEVER_SENT_CODES.has(e.code);exports.isNeverSentError=isNeverSentError;const MAX_RETRY_AFTER_MS=3e4,retryAfterMs=e=>{const
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.waitOrAbort=exports.retryAfterMs=exports.resendWhenUnanswered=exports.isRetryableStatus=exports.isRetryableRequest=exports.isRetryableFailure=exports.isNeverSentError=exports.isIdempotentMethod=exports.attachRetry=exports.IDEMPOTENCY_KEY_HEADER=void 0;var _axios=_interopRequireDefault(require("axios")),_index=require("../config/index.js"),_workspace=require("./workspace.js");function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}const IDEMPOTENCY_KEY_HEADER=exports.IDEMPOTENCY_KEY_HEADER="Idempotency-Key",isRetryableStatus=e=>"number"==typeof e&&(429===e||e>=500&&e<=599);exports.isRetryableStatus=isRetryableStatus;const IDEMPOTENT_METHODS=new Set(["get","head","options","put","delete"]),isIdempotentMethod=e=>IDEMPOTENT_METHODS.has(e.toLowerCase());exports.isIdempotentMethod=isIdempotentMethod;const NEVER_SENT_CODES=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN","ENETUNREACH","EHOSTUNREACH"]),isNeverSentError=e=>!e.response&&"string"==typeof e.code&&NEVER_SENT_CODES.has(e.code);exports.isNeverSentError=isNeverSentError;const MAX_RETRY_AFTER_MS=3e4,retryAfterMs=e=>{const t=e.response;if(!t)return null;const r=t.headers,s="function"==typeof r?.get?r.get("retry-after"):r?.["retry-after"],o=Number(s);return null!=s&&Number.isFinite(o)&&o>0?1e3*o:null};exports.retryAfterMs=retryAfterMs;const hasIdempotencyKey=e=>{const t=e?.headers,r="function"==typeof t?.get?t.get(IDEMPOTENCY_KEY_HEADER):t?.[IDEMPOTENCY_KEY_HEADER];return"string"==typeof r&&""!==r},isRetryableRequest=e=>void 0===e.status?e.idempotent:!!isRetryableStatus(e.status)&&(!(null!==e.namedWaitMs&&e.namedWaitMs>3e4)&&(e.idempotent||(429===e.status||503===e.status)&&e.hasIdempotencyKey));exports.isRetryableRequest=isRetryableRequest;const isRetryableFailure=e=>!_axios.default.isCancel(e)&&"ERR_CANCELED"!==e.code&&(!!isNeverSentError(e)||isRetryableRequest({idempotent:isIdempotentMethod(e.config?.method??"get"),status:e.response?.status,namedWaitMs:retryAfterMs(e),hasIdempotencyKey:hasIdempotencyKey(e.config)}));exports.isRetryableFailure=isRetryableFailure;const resendWhenUnanswered=exports.resendWhenUnanswered={retries:1,shouldRetry:e=>isRetryableFailure(e)||!e.response&&!_axios.default.isCancel(e)&&"ERR_CANCELED"!==e.code},DEFAULT_POLICY={retryDelayMs:e=>Math.random()*Math.min(2e3,500*2**(e-1)),shouldRetry:isRetryableFailure,onRetry:()=>{}},waitOrAbort=(e,t)=>new Promise(r=>{const onAbort=()=>{clearTimeout(s),r(!1)},s=setTimeout(()=>{t?.removeEventListener?.("abort",onAbort),r(!0)},e);t?.addEventListener?.("abort",onAbort,{once:!0})});exports.waitOrAbort=waitOrAbort;const attachRetry=(e,t={})=>{e.interceptors.response.use(void 0,async r=>{const s=r,o=s?.config;if(!o||!1===o.retry||(0,_workspace.isWorkspaceChangedResponse)(s))return Promise.reject(r);const n="object"==typeof o.retry?o.retry:{},a={...DEFAULT_POLICY,retries:(0,_index.getConfigValue)("retries"),...t,...n},i=(o.__retryAttempt??0)+1;if(i>a.retries||!a.shouldRetry(s))return Promise.reject(r);if(o.signal?.aborted)return Promise.reject(r);o.__retryAttempt=i,1===i&&(o.__retryStartedAt=Date.now()),o.transformRequest=[e=>e];const E=retryAfterMs(s)??a.retryDelayMs(i),u=o.__retryStartedAt??Date.now();if(Date.now()-u+E>2e4)return Promise.reject(r);a.onRetry(i,s);return await waitOrAbort(E,o.signal)?e.request(o):Promise.reject(r)})};exports.attachRetry=attachRetry;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.waitForSessionReplacement=exports.storeReplacementSession=exports.sessionDetailOf=exports.sessionCodeOf=exports.resetRefreshState=exports.refreshAccessToken=exports.queueBehindRefresh=exports.isRefreshInFlight=exports.injectUserAuth=exports.injectStore=exports.getRefreshPath=exports.getErrorMessage=exports.getAccountIdProvider=exports.endSessionAndLogout=exports.dispatchLogout=exports.currentTokenIfReplaced=exports.beginSessionReplacement=exports.SESSION_REVOKED_CODE=exports.SESSION_EXPIRED_CODE=void 0;var _axios=_interopRequireDefault(require("axios")),_authStore=require("../auth/authStore.js"),_index=require("../logger/index.js"),_publicClient=_interopRequireDefault(require("./publicClient.js"));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}const SESSION_REVOKED_CODE=exports.SESSION_REVOKED_CODE="session_revoked",SESSION_EXPIRED_CODE=exports.SESSION_EXPIRED_CODE="session_expired";let store,auth;const injectStore=e=>{store=e};exports.injectStore=injectStore;const injectUserAuth=e=>{auth=e};exports.injectUserAuth=injectUserAuth;let refreshTokenPromise=null,failedQueue=[];const processQueue=(e,
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.waitForSessionReplacement=exports.storeReplacementSession=exports.sessionDetailOf=exports.sessionCodeOf=exports.resetRefreshState=exports.refreshAccessToken=exports.queueBehindRefresh=exports.isSessionEnd=exports.isRefreshInFlight=exports.injectUserAuth=exports.injectStore=exports.getRefreshPath=exports.getErrorMessage=exports.getAccountIdProvider=exports.endSessionAndLogout=exports.dispatchLogout=exports.currentTokenIfReplaced=exports.beginSessionReplacement=exports.SessionEndedError=exports.SESSION_REVOKED_CODE=exports.SESSION_EXPIRED_CODE=void 0;var _axios=_interopRequireDefault(require("axios")),_authStore=require("../auth/authStore.js"),_index=require("../logger/index.js"),_publicClient=_interopRequireDefault(require("./publicClient.js"));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}const SESSION_REVOKED_CODE=exports.SESSION_REVOKED_CODE="session_revoked",SESSION_EXPIRED_CODE=exports.SESSION_EXPIRED_CODE="session_expired";class SessionEndedError extends Error{constructor(e){super(e),this.name="SessionEndedError",Object.setPrototypeOf(this,SessionEndedError.prototype)}}let store,auth;exports.SessionEndedError=SessionEndedError;const injectStore=e=>{store=e};exports.injectStore=injectStore;const injectUserAuth=e=>{auth=e};exports.injectUserAuth=injectUserAuth;let refreshTokenPromise=null,failedQueue=[];const processQueue=(e,s=null)=>{failedQueue.forEach(({resolve:r,reject:t})=>{e?t(e):null!==s&&r(s)}),failedQueue=[]},resetRefreshState=()=>{refreshTokenPromise=null,processQueue(new SessionEndedError("[@webority/mobile-core] Session ended"))};exports.resetRefreshState=resetRefreshState;const getErrorMessage=e=>e instanceof Error?e.message:"string"==typeof e?e:"Unknown error";exports.getErrorMessage=getErrorMessage;const requireAuth=()=>{if(!store||!auth)throw new Error("User package store is not initialized. Call initUserAuth first.");return{store:store,auth:auth}},getAccountIdProvider=()=>auth?.accountId;exports.getAccountIdProvider=getAccountIdProvider;const getRefreshPath=()=>auth?.refresh.path;exports.getRefreshPath=getRefreshPath;const dispatchLogout=async()=>{const e=requireAuth();await e.store.dispatch(e.auth.logout())};exports.dispatchLogout=dispatchLogout;const endSessionAndLogout=async(e,s,r=null)=>{await(0,_authStore.clearSession)(e,{code:s,detail:r}),await dispatchLogout()};exports.endSessionAndLogout=endSessionAndLogout;const sessionCodeOf=e=>{const s=e&&"object"==typeof e?e.code:void 0;return s===SESSION_REVOKED_CODE||s===SESSION_EXPIRED_CODE?s:null};exports.sessionCodeOf=sessionCodeOf;const sessionDetailOf=e=>{if(null===sessionCodeOf(e))return null;const s=e.detail;return"string"==typeof s&&""!==s?s:null};exports.sessionDetailOf=sessionDetailOf;const isRefreshInFlight=()=>null!==refreshTokenPromise;exports.isRefreshInFlight=isRefreshInFlight;let replacementCount=0,replacementSettled=Promise.resolve(),settleReplacement=null;const beginSessionReplacement=()=>{0===replacementCount&&(replacementSettled=new Promise(e=>{settleReplacement=e})),replacementCount+=1;let e=!1;return()=>{e||(e=!0,replacementCount-=1,0===replacementCount&&(settleReplacement?.(),settleReplacement=null))}};exports.beginSessionReplacement=beginSessionReplacement;const waitForSessionReplacement=()=>0===replacementCount?Promise.resolve():replacementSettled;exports.waitForSessionReplacement=waitForSessionReplacement;const currentTokenIfReplaced=async e=>{const s=(await(0,_authStore.getToken)(_authStore.ACCESS_TOKEN_KEY))?.token??null;return null!==s&&s!==e?s:null};exports.currentTokenIfReplaced=currentTokenIfReplaced;const queueBehindRefresh=()=>new Promise((e,s)=>{failedQueue.push({resolve:e,reject:s})});exports.queueBehindRefresh=queueBehindRefresh;const isSessionEnd=e=>e instanceof SessionEndedError||_axios.default.isAxiosError(e)&&(400===e.response?.status||401===e.response?.status);exports.isSessionEnd=isSessionEnd;const asString=(e,s)=>{if("string"!=typeof e||""===e)throw new Error(`The refresh response has no "${s}".`);return e},readWeborityTokens=e=>{const s=e??{};return{accessToken:asString(s.accessToken,"accessToken"),accessTokenExpiry:asString(s.accessTokenExpiration,"accessTokenExpiration"),refreshToken:asString(s.refreshToken,"refreshToken"),refreshTokenExpiry:asString(s.refreshTokenExpiration,"refreshTokenExpiration")}};class ReplacementTokensMissingError extends Error{constructor(e){super(`A session-replacing response carried no tokens: ${e}`),this.name="ReplacementTokensMissingError",Object.setPrototypeOf(this,ReplacementTokensMissingError.prototype)}}const storeReplacementSession=async e=>{let s;try{s=(auth?.refresh.readTokens??readWeborityTokens)(e)}catch(e){throw new ReplacementTokensMissingError(getErrorMessage(e))}await(0,_authStore.storeToken)(_authStore.ACCESS_TOKEN_KEY,s.accessToken,s.accessTokenExpiry),await(0,_authStore.storeToken)(_authStore.REFRESH_TOKEN_KEY,s.refreshToken,s.refreshTokenExpiry)};exports.storeReplacementSession=storeReplacementSession;const callRefreshEndpoint=async e=>{const s=await(0,_authStore.getToken)(_authStore.REFRESH_TOKEN_KEY);if(!s?.token)throw new SessionEndedError("No refresh token available");if(Date.parse(s.expiry)<=Date.now())throw new SessionEndedError("Refresh token expired");const r=await(0,_authStore.getToken)(_authStore.ACCESS_TOKEN_KEY),t={accessToken:r?.token??null,refreshToken:s.token},o=e.body?await e.body(t):t,n=e.headers?await e.headers():void 0;_index.Logger.info("Refreshing the access token");const{data:i}=await _publicClient.default.post(e.path,o,{...n?{headers:n}:{},skipErrorLog:!0}),a=(e.readTokens??readWeborityTokens)(i);if(await waitForSessionReplacement(),(await(0,_authStore.getToken)(_authStore.REFRESH_TOKEN_KEY))?.token!==s.token){const e=(await(0,_authStore.getToken)(_authStore.ACCESS_TOKEN_KEY))?.token;if(e)return _index.Logger.info("Keeping the session that replaced this one during the refresh"),e}return await(0,_authStore.storeToken)(_authStore.ACCESS_TOKEN_KEY,a.accessToken,a.accessTokenExpiry),await(0,_authStore.storeToken)(_authStore.REFRESH_TOKEN_KEY,a.refreshToken,a.refreshTokenExpiry),_index.Logger.info("Access token refreshed"),a.accessToken},endReason=e=>_axios.default.isAxiosError(e)?sessionCodeOf(e.response?.data)??`status ${e.response?.status}`:getErrorMessage(e),refreshAccessToken=()=>{if(refreshTokenPromise)return refreshTokenPromise;const e=(async()=>{let e=null;try{const{refresh:s}=requireAuth().auth;e=(await(0,_authStore.getToken)(_authStore.ACCESS_TOKEN_KEY))?.token??null;const r=await callRefreshEndpoint(s);return processQueue(null,r),r}catch(s){if(isSessionEnd(s)){await waitForSessionReplacement();const s=await currentTokenIfReplaced(e);if(s)return _index.Logger.info("The session was replaced during the refresh; continuing with the new one"),processQueue(null,s),s}const r=isSessionEnd(s);if(r)_index.Logger.info("Session ended, the refresh was refused:",endReason(s));else{const e=_axios.default.isAxiosError(s)?s.response?.data:void 0;_index.Logger.error("Token refresh failed:",e??getErrorMessage(s))}if(processQueue(s,null),r){const e=_axios.default.isAxiosError(s)&&401===s.response?.status,r=e?sessionCodeOf(s.response?.data):null,t=e?sessionDetailOf(s.response?.data):null;await endSessionAndLogout("rejected",r,t)}throw s}})().finally(()=>{refreshTokenPromise===e&&(refreshTokenPromise=null)});return refreshTokenPromise=e,e};exports.refreshAccessToken=refreshAccessToken;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.RequestOfflineError=void 0,Object.defineProperty(exports,"SESSION_EXPIRED_CODE",{enumerable:!0,get:function(){return _tokenRefresh.SESSION_EXPIRED_CODE}}),Object.defineProperty(exports,"SESSION_REVOKED_CODE",{enumerable:!0,get:function(){return _tokenRefresh.SESSION_REVOKED_CODE}}),exports.default=void 0,Object.defineProperty(exports,"injectStore",{enumerable:!0,get:function(){return _tokenRefresh.injectStore}}),Object.defineProperty(exports,"injectUserAuth",{enumerable:!0,get:function(){return _tokenRefresh.injectUserAuth}}),Object.defineProperty(exports,"resetRefreshState",{enumerable:!0,get:function(){return _tokenRefresh.resetRefreshState}});var _axios=_interopRequireWildcard(require("axios")),_authStore=require("../auth/authStore.js"),_index=require("../config/index.js"),_index2=require("../logger/index.js"),_networkStatus=require("../network/networkStatus.js");require("../types/axios.js");var cache,_baseUrl=require("./baseUrl.js"),_clientHeaders=require("./clientHeaders.js"),_curl=require("./curl.js"),_minAppVersion=require("./minAppVersion.js"),_multipart=require("./multipart.js"),_requestDefaults=require("./requestDefaults.js"),_responseBodyText=require("./responseBodyText.js"),_retry=require("./retry.js"),_tokenRefresh=require("./tokenRefresh.js"),_workspace=require("./workspace.js");function _interopRequireWildcard(e,r){if(!r&&e&&e.__esModule)return e;var t,s,n=Object.defineProperty,o={__proto__:null,default:e};if(Object(e)!==e)return o;if(cache||"function"!=typeof WeakMap||(cache=new WeakMap),cache){if(cache.has(e))return cache.get(e);cache.set(e,o)}for(s in e)"default"!==s&&{}.hasOwnProperty.call(e,s)&&((t=n&&Object.getOwnPropertyDescriptor(e,s))&&(t.get||t.set)?n(o,s,t):o[s]=e[s]);return o}class RequestOfflineError extends Error{constructor(e="Request blocked: device is offline"){super(e),this.name="RequestOfflineError",Object.setPrototypeOf(this,RequestOfflineError.prototype)}}exports.RequestOfflineError=RequestOfflineError;class NoAccessTokenError extends Error{constructor(){super("No access token available"),this.name="NoAccessTokenError",Object.setPrototypeOf(this,NoAccessTokenError.prototype)}}const endReplacement=e=>{e?._endReplacement?.(),e&&(e._endReplacement=void 0)},closeWindowIfTransformThrows=e=>{if(e._transformGuarded)return;e._transformGuarded=!0;const r=[].concat(e.transformRequest??[]);e.transformRequest=[function guarded(e,t){try{return r.reduce((e,r)=>r.call(this,e,t),e)}catch(e){throw endReplacement(this),e}}]},readSentToken=e=>{const r=e.headers instanceof _axios.AxiosHeaders?e.headers.get("Authorization"):void 0;return"string"==typeof r&&r.startsWith("Bearer ")?r.slice(7):null},userClient=_axios.default.create({headers:{"Content-Type":"application/json"}});(0,_minAppVersion.readMinAppVersion)(userClient),(0,_retry.attachRetry)(userClient);const setAuthHeader=(e,r)=>{e.headers instanceof _axios.AxiosHeaders?e.headers.set("Authorization",`Bearer ${r}`):e.headers=_axios.AxiosHeaders.from({...e.headers,Authorization:`Bearer ${r}`})},isRefreshTokenRequest=e=>{const r=(0,_tokenRefresh.getRefreshPath)();return!!r&&!!e?.includes(r)};userClient.interceptors.request.use(e=>{if(e.replacesSession&&!isRefreshTokenRequest(e.url)){const r=e;r._endReplacement=(0,_tokenRefresh.beginSessionReplacement)(),closeWindowIfTransformThrows(r)}return e}),(0,_baseUrl.applyConfiguredBaseUrl)(userClient),(0,_requestDefaults.applyRequestDefaults)(userClient),(0,_multipart.sendFormDataAsMultipart)(userClient),userClient.interceptors.request.use(e=>((0,_index.getConfigValue)("logCurl")&&(0,_curl.logCurl)(e),e)),(0,_clientHeaders.applyClientHeaders)(userClient),userClient.interceptors.request.use(async e=>{endReplacement(e);if(!1===(await(0,_networkStatus.getLastKnownNetworkStatus)()).isConnected)return _index2.Logger.warn(`Request blocked: device is offline. URL: ${e.url}`),Promise.reject(new RequestOfflineError);try{if(isRefreshTokenRequest(e.url))return e;await(0,_clientHeaders.stampAccountId)(e,(0,_tokenRefresh.getAccountIdProvider)());const r=await(0,_authStore.getToken)(_authStore.ACCESS_TOKEN_KEY);if(!r?.token)throw new NoAccessTokenError;const t=Date.now(),s=Date.parse(r.expiry);if(s<=t+3e4){_index2.Logger.info("Access token expired or about to expire, refreshing before request");const r=await(0,_tokenRefresh.refreshAccessToken)();setAuthHeader(e,r)}else setAuthHeader(e,r.token);return e}catch(r){return r instanceof NoAccessTokenError?_index2.Logger.info(`Request not sent: signed out. URL: ${e.url}`):_index2.Logger.error("Failed to attach token:",(0,_tokenRefresh.getErrorMessage)(r)),Promise.reject(r)}},e=>(_index2.Logger.error("Request error:",(0,_tokenRefresh.getErrorMessage)(e)),Promise.reject(e))),userClient.interceptors.response.use(async e=>{const r=e.config;if(r._endReplacement)try{await(0,_tokenRefresh.storeReplacementSession)(e.data)}finally{endReplacement(r)}return e},async e=>{if(endReplacement(e?.config),_axios.default.isCancel(e))return Promise.reject(e);if(e instanceof RequestOfflineError||e instanceof NoAccessTokenError)return Promise.reject(e);if(!_axios.default.isAxiosError(e))return _index2.Logger.error(`Non-axios error in response interceptor: ${(0,_tokenRefresh.getErrorMessage)(e)}`),Promise.reject(e);const r=e,t=r.config;if(!r.response)return t?.skipErrorLog||_index2.Logger.info(`Network error or no response from server: ${r.message}, URL: ${t?.url}`),Promise.reject(e);if((0,_workspace.isWorkspaceChangedResponse)(r))return _index2.Logger.info(`Refused for another workspace. URL: ${t?.url}`),Promise.reject(new _workspace.WorkspaceChangedError("Refused for another workspace",{response:r.response,config:t,cause:e}));if(401===r.response.status&&t&&!t._replayedWithCurrentToken&&!t.replacesSession
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.RequestOfflineError=void 0,Object.defineProperty(exports,"SESSION_EXPIRED_CODE",{enumerable:!0,get:function(){return _tokenRefresh.SESSION_EXPIRED_CODE}}),Object.defineProperty(exports,"SESSION_REVOKED_CODE",{enumerable:!0,get:function(){return _tokenRefresh.SESSION_REVOKED_CODE}}),exports.default=void 0,Object.defineProperty(exports,"injectStore",{enumerable:!0,get:function(){return _tokenRefresh.injectStore}}),Object.defineProperty(exports,"injectUserAuth",{enumerable:!0,get:function(){return _tokenRefresh.injectUserAuth}}),Object.defineProperty(exports,"resetRefreshState",{enumerable:!0,get:function(){return _tokenRefresh.resetRefreshState}});var _axios=_interopRequireWildcard(require("axios")),_authStore=require("../auth/authStore.js"),_index=require("../config/index.js"),_index2=require("../logger/index.js"),_networkStatus=require("../network/networkStatus.js");require("../types/axios.js");var cache,_baseUrl=require("./baseUrl.js"),_clientHeaders=require("./clientHeaders.js"),_curl=require("./curl.js"),_minAppVersion=require("./minAppVersion.js"),_multipart=require("./multipart.js"),_requestDefaults=require("./requestDefaults.js"),_responseBodyText=require("./responseBodyText.js"),_retry=require("./retry.js"),_tokenRefresh=require("./tokenRefresh.js"),_workspace=require("./workspace.js");function _interopRequireWildcard(e,r){if(!r&&e&&e.__esModule)return e;var t,s,n=Object.defineProperty,o={__proto__:null,default:e};if(Object(e)!==e)return o;if(cache||"function"!=typeof WeakMap||(cache=new WeakMap),cache){if(cache.has(e))return cache.get(e);cache.set(e,o)}for(s in e)"default"!==s&&{}.hasOwnProperty.call(e,s)&&((t=n&&Object.getOwnPropertyDescriptor(e,s))&&(t.get||t.set)?n(o,s,t):o[s]=e[s]);return o}class RequestOfflineError extends Error{constructor(e="Request blocked: device is offline"){super(e),this.name="RequestOfflineError",Object.setPrototypeOf(this,RequestOfflineError.prototype)}}exports.RequestOfflineError=RequestOfflineError;class NoAccessTokenError extends Error{constructor(){super("No access token available"),this.name="NoAccessTokenError",Object.setPrototypeOf(this,NoAccessTokenError.prototype)}}const endReplacement=e=>{e?._endReplacement?.(),e&&(e._endReplacement=void 0)},closeWindowIfTransformThrows=e=>{if(e._transformGuarded)return;e._transformGuarded=!0;const r=[].concat(e.transformRequest??[]);e.transformRequest=[function guarded(e,t){try{return r.reduce((e,r)=>r.call(this,e,t),e)}catch(e){throw endReplacement(this),e}}]},readSentToken=e=>{const r=e.headers instanceof _axios.AxiosHeaders?e.headers.get("Authorization"):void 0;return"string"==typeof r&&r.startsWith("Bearer ")?r.slice(7):null},userClient=_axios.default.create({headers:{"Content-Type":"application/json"}});(0,_minAppVersion.readMinAppVersion)(userClient),(0,_retry.attachRetry)(userClient);const setAuthHeader=(e,r)=>{e.headers instanceof _axios.AxiosHeaders?e.headers.set("Authorization",`Bearer ${r}`):e.headers=_axios.AxiosHeaders.from({...e.headers,Authorization:`Bearer ${r}`})},isRefreshTokenRequest=e=>{const r=(0,_tokenRefresh.getRefreshPath)();return!!r&&!!e?.includes(r)};userClient.interceptors.request.use(e=>{if(e.replacesSession&&!isRefreshTokenRequest(e.url)){const r=e;r._endReplacement=(0,_tokenRefresh.beginSessionReplacement)(),closeWindowIfTransformThrows(r)}return e}),(0,_baseUrl.applyConfiguredBaseUrl)(userClient),(0,_requestDefaults.applyRequestDefaults)(userClient),(0,_multipart.sendFormDataAsMultipart)(userClient),userClient.interceptors.request.use(e=>((0,_index.getConfigValue)("logCurl")&&(0,_curl.logCurl)(e),e)),(0,_clientHeaders.applyClientHeaders)(userClient),userClient.interceptors.request.use(async e=>{endReplacement(e);if(!1===(await(0,_networkStatus.getLastKnownNetworkStatus)()).isConnected)return _index2.Logger.warn(`Request blocked: device is offline. URL: ${e.url}`),Promise.reject(new RequestOfflineError);try{if(isRefreshTokenRequest(e.url))return e;await(0,_clientHeaders.stampAccountId)(e,(0,_tokenRefresh.getAccountIdProvider)());const r=await(0,_authStore.getToken)(_authStore.ACCESS_TOKEN_KEY);if(!r?.token)throw new NoAccessTokenError;const t=Date.now(),s=Date.parse(r.expiry);if(s<=t+3e4){_index2.Logger.info("Access token expired or about to expire, refreshing before request");const r=await(0,_tokenRefresh.refreshAccessToken)();setAuthHeader(e,r)}else setAuthHeader(e,r.token);return e}catch(r){return r instanceof NoAccessTokenError?_index2.Logger.info(`Request not sent: signed out. URL: ${e.url}`):(0,_tokenRefresh.isSessionEnd)(r)||_index2.Logger.error("Failed to attach token:",(0,_tokenRefresh.getErrorMessage)(r)),Promise.reject(r)}},e=>(_index2.Logger.error("Request error:",(0,_tokenRefresh.getErrorMessage)(e)),Promise.reject(e))),userClient.interceptors.response.use(async e=>{const r=e.config;if(r._endReplacement)try{await(0,_tokenRefresh.storeReplacementSession)(e.data)}finally{endReplacement(r)}return e},async e=>{if(endReplacement(e?.config),_axios.default.isCancel(e))return Promise.reject(e);if(e instanceof RequestOfflineError||e instanceof NoAccessTokenError||e instanceof _tokenRefresh.SessionEndedError)return Promise.reject(e);if(!_axios.default.isAxiosError(e))return _index2.Logger.error(`Non-axios error in response interceptor: ${(0,_tokenRefresh.getErrorMessage)(e)}`),Promise.reject(e);const r=e,t=r.config;if(!r.response)return t?.skipErrorLog||_index2.Logger.info(`Network error or no response from server: ${r.message}, URL: ${t?.url}`),Promise.reject(e);if((0,_workspace.isWorkspaceChangedResponse)(r))return _index2.Logger.info(`Refused for another workspace. URL: ${t?.url}`),Promise.reject(new _workspace.WorkspaceChangedError("Refused for another workspace",{response:r.response,config:t,cause:e}));if(isRefreshTokenRequest(t?.url))return Promise.reject(e);if(401===r.response.status&&t&&!t._replayedWithCurrentToken&&!t.replacesSession&&(await(0,_tokenRefresh.waitForSessionReplacement)(),await(0,_tokenRefresh.currentTokenIfReplaced)(readSentToken(t)))){const r=await(0,_clientHeaders.readAccountId)((0,_tokenRefresh.getAccountIdProvider)());return(t._accountId??null)!==r?(_index2.Logger.info(`Workspace changed in flight; not sent again. URL: ${t.url}`),Promise.reject(new _workspace.WorkspaceChangedError("Workspace changed in flight",{config:t,cause:e}))):(_index2.Logger.info(`Session changed while the request was in flight; sending it again. URL: ${t.url}`),t._replayedWithCurrentToken=!0,userClient(t))}if(401===r.response.status&&t&&!t._retry){const s=(0,_tokenRefresh.sessionCodeOf)(r.response.data);if(null!==s)return _index2.Logger.warn(`Session ${s}, logging out without refresh. URL: ${t.url}`),(0,_tokenRefresh.resetRefreshState)(),await(0,_tokenRefresh.endSessionAndLogout)("terminated",s,(0,_tokenRefresh.sessionDetailOf)(r.response.data)),Promise.reject(e);if(_index2.Logger.warn(`Unauthorized URL: ${t.url}`),t._retry=!0,(0,_tokenRefresh.isRefreshInFlight)())return(0,_tokenRefresh.queueBehindRefresh)().then(e=>(_index2.Logger.info("Retrying request after token refresh:",t.url),setAuthHeader(t,e),userClient(t))).catch(e=>((0,_tokenRefresh.isSessionEnd)(e)||_index2.Logger.error("Failed to retry request after token refresh:",(0,_tokenRefresh.getErrorMessage)(e)),Promise.reject(e)));try{const e=await(0,_tokenRefresh.refreshAccessToken)();return setAuthHeader(t,e),userClient(t)}catch(e){return Promise.reject(e)}}return t?.skipErrorLog||_index2.Logger.error(`Response error: ${(0,_responseBodyText.responseBodyText)(r.response?.data,r.message)}, URL: ${t?.url}, Status: ${r.response.status}`),Promise.reject(e)});var _default=exports.default=userClient;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.storeToken=exports.storeSessionUser=exports.setLegacyTokenKeys=exports.setKeychainImplementation=exports.removeToken=exports.removeSessionUser=exports.getToken=exports.getSessionUser=exports.clearSession=exports.addSessionEndedListener=exports.SESSION_USER_KEY=exports.REFRESH_TOKEN_KEY=exports.LEGACY_REFRESH_TOKEN_LIFETIME_MS=exports.ACCESS_TOKEN_KEY=void 0;var cache,SecureStore=_interopRequireWildcard(require("expo-secure-store")),_index=require("../logger/index.js"),_index2=require("../storage/index.js"),_jwt=require("./jwt.js");function _interopRequireWildcard(e,r){if(!r&&e&&e.__esModule)return e;var t,n,o=Object.defineProperty,s={__proto__:null,default:e};if(Object(e)!==e)return s;if(cache||"function"!=typeof WeakMap||(cache=new WeakMap),cache){if(cache.has(e))return cache.get(e);cache.set(e,s)}for(n in e)"default"!==n&&{}.hasOwnProperty.call(e,n)&&((t=o&&Object.getOwnPropertyDescriptor(e,n))&&(t.get||t.set)?o(s,n,t):s[n]=e[n]);return s}const ACCESS_TOKEN_KEY=exports.ACCESS_TOKEN_KEY="accessToken",REFRESH_TOKEN_KEY=exports.REFRESH_TOKEN_KEY="refreshToken",SESSION_USER_KEY=exports.SESSION_USER_KEY="sessionUser",LEGACY_REFRESH_TOKEN_LIFETIME_MS=exports.LEGACY_REFRESH_TOKEN_LIFETIME_MS=2592e6;let backend=null;const keyFor=e=>(e??"default").replace(/[^A-Za-z0-9._-]/g,"_"),expoSecureStoreBackend={setGenericPassword:async(e,r,t)=>(await SecureStore.setItemAsync(keyFor(t?.service),JSON.stringify({username:e,password:r})),!0),getGenericPassword:async e=>{const r=e?.service,t=await SecureStore.getItemAsync(keyFor(r));if(null===t)return!1;const n=JSON.parse(t);return{username:n.username,password:n.password,service:r??"default"}},resetGenericPassword:async e=>(await SecureStore.deleteItemAsync(keyFor(e?.service)),!0)},resolveBackend=()=>backend??expoSecureStoreBackend,memo=new Map;let generation=0;const forget=e=>{generation+=1,void 0===e?memo.clear():memo.delete(e)},requireBackend=e=>{const r=resolveBackend();if(!r){const r=new Error(`[authStore] no secure-store backend available; cannot ${e}.`);throw _index.Logger.error(r.message),r}return r},setKeychainImplementation=e=>{backend=e,forget()};exports.setKeychainImplementation=setKeychainImplementation;const storeToken=async(e,r,t)=>{_index.Logger.info(`Storing token for key: ${e}`),forget(e);try{const n=JSON.stringify({token:r,expiry:t});await requireBackend("store a token").setGenericPassword("token",n,{service:e}),forget(e),memo.set(e,{token:r,expiry:t}),_index.Logger.info(`Token stored successfully for key: ${e}`)}catch(r){throw forget(e),_index.Logger.error(`Error storing token for key: ${e}`,r),r}};exports.storeToken=storeToken;const parseTokenData=e=>{if(!e)return null;const{password:r}=e;try{const e=JSON.parse(r);return e&&"object"==typeof e&&"token"in e&&"expiry"in e&&"string"==typeof e.token&&"string"==typeof e.expiry?e:null}catch{return null}},getToken=async e=>{if(isSessionKey(e)&&legacyKeys&&await migrateLegacySession(),memo.has(e))return memo.get(e)??null;const r=generation;try{const t=await requireBackend("read a token").getGenericPassword({service:e});let n=null;if(t){const r=parseTokenData(t);if(r)n={token:r.token,expiry:r.expiry};else if(_index.Logger.warn(`Stored credentials for key "${e}" are not a valid token; ignoring them.`),isSessionKey(e))return await endSession("corrupt",!0),null}return r===generation&&memo.set(e,n),n}catch(r){const t=r instanceof Error?r.message:String(r);return t.includes("Key permanently invalidated")||t.includes("Secret invalidated")?(_index.Logger.error(`Stored token for key "${e}" can no longer be decrypted; clearing it.`),isSessionKey(e)?await endSession("corrupt",!0):await removeToken(e),null):(_index.Logger.error(`Error retrieving token for key: ${e}`,r),null)}};exports.getToken=getToken;const removeToken=async e=>{forget(e);try{await requireBackend("remove a token").resetGenericPassword({service:e}),_index.Logger.info(`Token removed successfully for key: ${e}`)}catch(r){if(r instanceof Error&&r.message.includes("Item not found"))return void _index.Logger.info(`No token found to remove for key: ${e}`);_index.Logger.error(`Failed to remove token for key: ${e}`,r)}finally{forget(e)}};exports.removeToken=removeToken;const isSessionKey=e=>e===ACCESS_TOKEN_KEY||e===REFRESH_TOKEN_KEY,storeSessionUser=async e=>{if(!await _index2.Storage.setItem(SESSION_USER_KEY,JSON.stringify(e)))throw new Error("[authStore] could not store the session user.")};exports.storeSessionUser=storeSessionUser;const getSessionUser=async()=>{const e=await _index2.Storage.getItem(SESSION_USER_KEY);if(null===e)return null;try{return JSON.parse(e)}catch{return _index.Logger.warn("The stored session user is not valid JSON; clearing it."),await removeSessionUser(),null}};exports.getSessionUser=getSessionUser;const removeSessionUser=async()=>{await _index2.Storage.removeItem(SESSION_USER_KEY)};exports.removeSessionUser=removeSessionUser;let legacyKeys=null,legacyCheck=null;const setLegacyTokenKeys=e=>{legacyKeys=e,legacyCheck=null};exports.setLegacyTokenKeys=setLegacyTokenKeys;const readLegacyToken=e=>{try{const r=JSON.parse(e);if("string"==typeof r)return""===r.trim()?null:{token:r,expiry:null};if(r&&"object"==typeof r&&"string"==typeof r.token&&"string"==typeof r.expiry)return r}catch{}return""===e.trim()?null:{token:e,expiry:null}},expiryOf=e=>3===e.split(".").length?(0,_jwt.getJWTExpiry)(e)?.toISOString()??null:null,readLegacyRaw=async e=>{const r=await resolveBackend().getGenericPassword({service:e});return r?r.password:null},migrateLegacySession=()=>{if(!legacyKeys)return Promise.resolve();if(legacyCheck)return legacyCheck;const e=legacyKeys;return legacyCheck=(async()=>{try{const r=resolveBackend()
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.storeToken=exports.storeSessionUser=exports.setLegacyTokenKeys=exports.setKeychainImplementation=exports.removeToken=exports.removeSessionUser=exports.getToken=exports.getSessionUser=exports.clearSession=exports.addSessionEndedListener=exports.SESSION_USER_KEY=exports.REFRESH_TOKEN_KEY=exports.LEGACY_REFRESH_TOKEN_LIFETIME_MS=exports.ACCESS_TOKEN_KEY=void 0;var cache,SecureStore=_interopRequireWildcard(require("expo-secure-store")),_index=require("../logger/index.js"),_index2=require("../storage/index.js"),_jwt=require("./jwt.js");function _interopRequireWildcard(e,r){if(!r&&e&&e.__esModule)return e;var t,n,o=Object.defineProperty,s={__proto__:null,default:e};if(Object(e)!==e)return s;if(cache||"function"!=typeof WeakMap||(cache=new WeakMap),cache){if(cache.has(e))return cache.get(e);cache.set(e,s)}for(n in e)"default"!==n&&{}.hasOwnProperty.call(e,n)&&((t=o&&Object.getOwnPropertyDescriptor(e,n))&&(t.get||t.set)?o(s,n,t):s[n]=e[n]);return s}const ACCESS_TOKEN_KEY=exports.ACCESS_TOKEN_KEY="accessToken",REFRESH_TOKEN_KEY=exports.REFRESH_TOKEN_KEY="refreshToken",SESSION_USER_KEY=exports.SESSION_USER_KEY="sessionUser",LEGACY_REFRESH_TOKEN_LIFETIME_MS=exports.LEGACY_REFRESH_TOKEN_LIFETIME_MS=2592e6;let backend=null;const keyFor=e=>(e??"default").replace(/[^A-Za-z0-9._-]/g,"_"),expoSecureStoreBackend={setGenericPassword:async(e,r,t)=>(await SecureStore.setItemAsync(keyFor(t?.service),JSON.stringify({username:e,password:r})),!0),getGenericPassword:async e=>{const r=e?.service,t=await SecureStore.getItemAsync(keyFor(r));if(null===t)return!1;const n=JSON.parse(t);return{username:n.username,password:n.password,service:r??"default"}},resetGenericPassword:async e=>(await SecureStore.deleteItemAsync(keyFor(e?.service)),!0)},resolveBackend=()=>backend??expoSecureStoreBackend,memo=new Map;let generation=0;const forget=e=>{generation+=1,void 0===e?memo.clear():memo.delete(e)},requireBackend=e=>{const r=resolveBackend();if(!r){const r=new Error(`[authStore] no secure-store backend available; cannot ${e}.`);throw _index.Logger.error(r.message),r}return r},setKeychainImplementation=e=>{backend=e,forget()};exports.setKeychainImplementation=setKeychainImplementation;const storeToken=async(e,r,t)=>{_index.Logger.info(`Storing token for key: ${e}`),forget(e);try{const n=JSON.stringify({token:r,expiry:t});await requireBackend("store a token").setGenericPassword("token",n,{service:e}),forget(e),memo.set(e,{token:r,expiry:t}),_index.Logger.info(`Token stored successfully for key: ${e}`)}catch(r){throw forget(e),_index.Logger.error(`Error storing token for key: ${e}`,r),r}};exports.storeToken=storeToken;const parseTokenData=e=>{if(!e)return null;const{password:r}=e;try{const e=JSON.parse(r);return e&&"object"==typeof e&&"token"in e&&"expiry"in e&&"string"==typeof e.token&&"string"==typeof e.expiry?e:null}catch{return null}},getToken=async e=>{if(isSessionKey(e)&&legacyKeys&&await migrateLegacySession(),memo.has(e))return memo.get(e)??null;const r=generation;try{const t=await requireBackend("read a token").getGenericPassword({service:e});let n=null;if(t){const r=parseTokenData(t);if(r)n={token:r.token,expiry:r.expiry};else if(_index.Logger.warn(`Stored credentials for key "${e}" are not a valid token; ignoring them.`),isSessionKey(e))return await endSession("corrupt",!0),null}return r===generation&&memo.set(e,n),n}catch(r){const t=r instanceof Error?r.message:String(r);return t.includes("Key permanently invalidated")||t.includes("Secret invalidated")?(_index.Logger.error(`Stored token for key "${e}" can no longer be decrypted; clearing it.`),isSessionKey(e)?await endSession("corrupt",!0):await removeToken(e),null):(_index.Logger.error(`Error retrieving token for key: ${e}`,r),null)}};exports.getToken=getToken;const removeToken=async e=>{forget(e);try{await requireBackend("remove a token").resetGenericPassword({service:e}),_index.Logger.info(`Token removed successfully for key: ${e}`)}catch(r){if(r instanceof Error&&r.message.includes("Item not found"))return void _index.Logger.info(`No token found to remove for key: ${e}`);_index.Logger.error(`Failed to remove token for key: ${e}`,r)}finally{forget(e)}};exports.removeToken=removeToken;const isSessionKey=e=>e===ACCESS_TOKEN_KEY||e===REFRESH_TOKEN_KEY,storeSessionUser=async e=>{if(!await _index2.Storage.setItem(SESSION_USER_KEY,JSON.stringify(e)))throw new Error("[authStore] could not store the session user.")};exports.storeSessionUser=storeSessionUser;const getSessionUser=async()=>{const e=await _index2.Storage.getItem(SESSION_USER_KEY);if(null===e)return null;try{return JSON.parse(e)}catch{return _index.Logger.warn("The stored session user is not valid JSON; clearing it."),await removeSessionUser(),null}};exports.getSessionUser=getSessionUser;const removeSessionUser=async()=>{await _index2.Storage.removeItem(SESSION_USER_KEY)};exports.removeSessionUser=removeSessionUser;let legacyKeys=null,legacyCheck=null;const setLegacyTokenKeys=e=>{legacyKeys=e,legacyCheck=null};exports.setLegacyTokenKeys=setLegacyTokenKeys;const readLegacyToken=e=>{try{const r=JSON.parse(e);if("string"==typeof r)return""===r.trim()?null:{token:r,expiry:null};if(r&&"object"==typeof r&&"string"==typeof r.token&&"string"==typeof r.expiry)return r}catch{}return""===e.trim()?null:{token:e,expiry:null}},expiryOf=e=>3===e.split(".").length?(0,_jwt.getJWTExpiry)(e)?.toISOString()??null:null,readLegacyRaw=async e=>{const r=await resolveBackend().getGenericPassword({service:e});return r?r.password:null},migrateLegacySession=()=>{if(!legacyKeys)return Promise.resolve();if(legacyCheck)return legacyCheck;const e=legacyKeys;return legacyCheck=(async()=>{try{const r=resolveBackend();let t=!0;const n=!await r.getGenericPassword({service:ACCESS_TOKEN_KEY})&&!await r.getGenericPassword({service:REFRESH_TOKEN_KEY}),o=await readLegacyRaw(e.accessToken),s=await readLegacyRaw(e.refreshToken);if(n&&(null!==o||null!==s)){const n=null===o?null:readLegacyToken(o),i=null===s?null:readLegacyToken(s);if(n){const e=n.expiry??expiryOf(n.token)??(new Date).toISOString();await r.setGenericPassword("token",JSON.stringify({token:n.token,expiry:e}),{service:ACCESS_TOKEN_KEY})}if(i){const e=i.expiry??expiryOf(i.token)??new Date(Date.now()+LEGACY_REFRESH_TOKEN_LIFETIME_MS).toISOString();await r.setGenericPassword("token",JSON.stringify({token:i.token,expiry:e}),{service:REFRESH_TOKEN_KEY})}if(e.sessionUser){const r=await _index2.Storage.getItem(e.sessionUser);null!==r&&(t=await _index2.Storage.setItem(SESSION_USER_KEY,r),t||_index.Logger.error("[authStore] could not copy the cached user from the legacy key; leaving it in place"))}null===n&&null===i||(forget(),_index.Logger.breadcrumb("[authStore] moved a session from the legacy token keys"))}for(const t of[e.accessToken,e.refreshToken])await r.resetGenericPassword({service:t}).catch(()=>{});e.sessionUser&&t&&await _index2.Storage.removeItem(e.sessionUser)}catch(e){_index.Logger.error("[authStore] could not move the session from the legacy token keys",e)}})(),legacyCheck},listeners=new Set,emitSessionEnded=(e,r)=>{for(const t of[...listeners])try{t(e,r)}catch(e){_index.Logger.error("[authStore] a session-ended listener threw",e)}},addSessionEndedListener=e=>(listeners.add(e),()=>{listeners.delete(e)});exports.addSessionEndedListener=addSessionEndedListener;const endSession=async(e,r,t=null,n=null)=>{const o=r||null!==await getToken(ACCESS_TOKEN_KEY)||null!==await getToken(REFRESH_TOKEN_KEY);await removeToken(ACCESS_TOKEN_KEY),await removeToken(REFRESH_TOKEN_KEY),await removeSessionUser(),o&&emitSessionEnded(e,{code:t,detail:n})},clearSession=async(e="signedOut",r={})=>endSession(e,!1,r.code??null,r.detail??null);exports.clearSession=clearSession;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.adaptExpoFileSystem=void 0;const asDirectoryPath=e=>e.replace(/\/+$/,""),adaptExpoFileSystem=e=>{const t=e?.default??e;if("function"!=typeof t?.File||"function"!=typeof t.File.prototype?.write)return null;const{File:r,Directory:i,Paths:
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.adaptExpoFileSystem=void 0;const asDirectoryPath=e=>e.replace(/\/+$/,""),adaptExpoFileSystem=e=>{const t=e?.default??e;if("function"!=typeof t?.File||"function"!=typeof t.File.prototype?.write)return null;const{File:r,Directory:i,Paths:s}=t,o=asDirectoryPath(s.document.uri);return{dirs:{documents:o,cache:asDirectoryPath(s.cache.uri),downloads:o},write:async(e,t)=>{const i=new r(e);i.create({intermediates:!0,overwrite:!0}),await i.write(t)},exists:e=>Promise.resolve(new r(e).exists),stat:e=>Promise.resolve({size:new r(e).size}),unlink:e=>(new r(e).delete(),Promise.resolve()),mkdir:e=>(new i(e).create({intermediates:!0,idempotent:!0}),Promise.resolve())}};exports.adaptExpoFileSystem=adaptExpoFileSystem;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.withdrawBroadcastConsent=exports.initPushBroadcasts=exports.handleBroadcastOpen=exports.handleBroadcastAction=exports.grantBroadcastConsent=exports.getBroadcastConsent=exports.BROADCAST_OPT_OUT_ACTION=void 0;var _reactNative=require("react-native"),_publicClient=_interopRequireDefault(require("../api/publicClient.js")),_userClient=_interopRequireDefault(require("../api/userClient.js")),_index=require("../config/index.js"),_index2=require("../errors/index.js"),_index3=require("../logger/index.js"),_push=require("./push.js");function _interopRequireDefault(t){return t&&t.__esModule?t:{default:t}}const BROADCAST_OPT_OUT_ACTION=exports.BROADCAST_OPT_OUT_ACTION="broadcast-opt-out",WITHDRAW_FROM_PUSH_ROUTE="/consent/withdraw-from-push",OPENS_ROUTE="/opens";let broadcastsConfig=null;const reportedOpens=new Set,requireBroadcastsConfig=()=>{if(!broadcastsConfig)throw new Error("[@webority/mobile-core] call initPushBroadcasts before using push broadcasts.");return broadcastsConfig},clientName=()=>[_reactNative.Platform.OS,(0,_index.getConfigValue)("appId"),(0,_index.getConfigValue)("appVersion")].filter(Boolean).join(" "),toConsent=t=>({status:t.status,statusDateTimeUtc:t.statusDateTimeUtc??null}),initPushBroadcasts=t=>{if(!t.basePath.startsWith("/")||t.basePath.endsWith("/"))throw new Error("[@webority/mobile-core] PushBroadcastsConfig.basePath must start with / and not end with /.");broadcastsConfig=t,(0,_push.setCategories)([{id:t.categoryId,actions:[{id:BROADCAST_OPT_OUT_ACTION,title:t.optOutTitle,opensApp:!1}]}]).catch(t=>_index3.Logger.error("[push] registering the broadcast category failed",t))};exports.initPushBroadcasts=initPushBroadcasts;const getBroadcastConsent=async()=>{const{basePath:t}=requireBroadcastsConfig();try{const e=await _userClient.default.get(`${t}/consent`);return toConsent(e.data)}catch(t){throw(0,_index2.extractApiError)(t)}};exports.getBroadcastConsent=getBroadcastConsent;const grantBroadcastConsent=async()=>{const{basePath:t,consentTextVersion:e}=requireBroadcastsConfig();try{const
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.withdrawBroadcastConsent=exports.initPushBroadcasts=exports.handleBroadcastOpen=exports.handleBroadcastAction=exports.grantBroadcastConsent=exports.getBroadcastConsent=exports.BROADCAST_OPT_OUT_ACTION=void 0;var _reactNative=require("react-native"),_publicClient=_interopRequireDefault(require("../api/publicClient.js")),_userClient=_interopRequireDefault(require("../api/userClient.js")),_index=require("../config/index.js"),_index2=require("../errors/index.js"),_index3=require("../logger/index.js"),_index4=require("../storage/index.js"),_push=require("./push.js");function _interopRequireDefault(t){return t&&t.__esModule?t:{default:t}}const BROADCAST_OPT_OUT_ACTION=exports.BROADCAST_OPT_OUT_ACTION="broadcast-opt-out",WITHDRAW_FROM_PUSH_ROUTE="/consent/withdraw-from-push",OPENS_ROUTE="/opens",PENDING_OPT_OUTS_KEY="@webority/push/pending-opt-outs";let broadcastsConfig=null;const reportedOpens=new Set,requireBroadcastsConfig=()=>{if(!broadcastsConfig)throw new Error("[@webority/mobile-core] call initPushBroadcasts before using push broadcasts.");return broadcastsConfig},readPendingOptOuts=async()=>{const t=await _index4.Storage.getJson(PENDING_OPT_OUTS_KEY);return Array.isArray(t)?t.filter(t=>"string"==typeof t):[]},savePendingOptOuts=t=>t.length>0?_index4.Storage.setJson(PENDING_OPT_OUTS_KEY,t):_index4.Storage.removeItem(PENDING_OPT_OUTS_KEY),isRefusal=t=>t>=400&&t<500&&408!==t&&429!==t,sendOptOuts=async(t,e)=>{const s=await readPendingOptOuts();void 0===e||s.includes(e)||(s.push(e),await savePendingOptOuts(s));for(const e of[...s]){try{await _publicClient.default.post(`${t.basePath}${WITHDRAW_FROM_PUSH_ROUTE}`,{token:e})}catch(t){const{status:e}=(0,_index2.extractApiError)(t);if(!isRefusal(e)){_index3.Logger.error(`[push] ${WITHDRAW_FROM_PUSH_ROUTE} failed with status ${e}; the opt-out stays stored and is sent again at the next launch`);continue}_index3.Logger.error(`[push] ${WITHDRAW_FROM_PUSH_ROUTE} was refused with status ${e}; the opt-out is dropped`)}s.splice(s.indexOf(e),1),await savePendingOptOuts(s)}};let outbox=Promise.resolve();const queueOptOuts=(t,e)=>(outbox=outbox.then(()=>sendOptOuts(t,e)),outbox),clientName=()=>[_reactNative.Platform.OS,(0,_index.getConfigValue)("appId"),(0,_index.getConfigValue)("appVersion")].filter(Boolean).join(" "),toConsent=t=>({status:t.status,statusDateTimeUtc:t.statusDateTimeUtc??null}),initPushBroadcasts=t=>{if(!t.basePath.startsWith("/")||t.basePath.endsWith("/"))throw new Error("[@webority/mobile-core] PushBroadcastsConfig.basePath must start with / and not end with /.");broadcastsConfig=t,(0,_push.setCategories)([{id:t.categoryId,actions:[{id:BROADCAST_OPT_OUT_ACTION,title:t.optOutTitle,opensApp:!1}]}]).catch(t=>_index3.Logger.error("[push] registering the broadcast category failed",t)),queueOptOuts(t)};exports.initPushBroadcasts=initPushBroadcasts;const getBroadcastConsent=async()=>{const{basePath:t}=requireBroadcastsConfig();try{const e=await _userClient.default.get(`${t}/consent`);return toConsent(e.data)}catch(t){throw(0,_index2.extractApiError)(t)}};exports.getBroadcastConsent=getBroadcastConsent;const grantBroadcastConsent=async()=>{const{basePath:t,consentTextVersion:e}=requireBroadcastsConfig();try{const s=await _userClient.default.post(`${t}/consent/grant`,{consentTextVersion:e,source:"MobileApp",client:clientName()});return toConsent(s.data)}catch(t){throw(0,_index2.extractApiError)(t)}};exports.grantBroadcastConsent=grantBroadcastConsent;const withdrawBroadcastConsent=async()=>{const{basePath:t}=requireBroadcastsConfig();try{const e=await _userClient.default.post(`${t}/consent/withdraw`,{source:"MobileApp",broadcastRecipientId:null,client:clientName()});return toConsent(e.data)}catch(t){throw(0,_index2.extractApiError)(t)}};exports.withdrawBroadcastConsent=withdrawBroadcastConsent;const handleBroadcastAction=async t=>{if(t.actionId!==BROADCAST_OPT_OUT_ACTION||"Broadcast"!==t.data.kind)return;if(!broadcastsConfig)return void _index3.Logger.error("[push] a broadcast opt-out arrived before initPushBroadcasts; call it at module scope in the entry file");const e=t.data.optOutToken;e?await queueOptOuts(broadcastsConfig,e):_index3.Logger.error("[push] a broadcast opt-out carried no token")};exports.handleBroadcastAction=handleBroadcastAction;const handleBroadcastOpen=t=>{const e=t.broadcastRecipientId;"Broadcast"===t.kind&&e&&(broadcastsConfig?reportedOpens.has(e)||(reportedOpens.add(e),_userClient.default.post(`${broadcastsConfig.basePath}/opens`,{broadcastRecipientId:e}).catch(t=>_index3.Logger.warn(`[push] /opens failed with status ${(0,_index2.extractApiError)(t).status}`))):_index3.Logger.error("[push] a broadcast open arrived before initPushBroadcasts; call it at module scope in the entry file"))};exports.handleBroadcastOpen=handleBroadcastOpen;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.usePush=exports.toPushReceived=exports.toPushAction=exports.toNotificationActions=exports.setPushImplementation=exports.setCategories=exports.setBadgeCount=exports.routeTaskPayload=exports.resolveModules=exports.resetPush=exports.readDevicePushToken=exports.onReceive=exports.onAction=exports.notifyLocal=exports.initPush=exports.enablePush=exports.dismissAllNotifications=exports.disablePush=void 0;var _react=require("react"),_reactNative=require("react-native"),_index=require("../logger/index.js");let resolved,override=null;const setPushImplementation=e=>{override=e};exports.setPushImplementation=setPushImplementation;const resolveModules=()=>{if(override)return override;if(void 0!==resolved)return resolved;try{if(require("expo").isRunningInExpoGo())return resolved=null,resolved;const e=require("expo-notifications"),t=require("expo-application");resolved={notifications:e,applicationId:t.applicationId,getApnsEnvironment:()=>t.getIosPushNotificationServiceEnvironmentAsync()}}catch(e){_index.Logger.warn("[push] expo-notifications is not available; push is off",e),resolved=null}return resolved};exports.resolveModules=resolveModules;let state={status:"unknown",enabled:!1};const subscribers=new Set,setState=e=>{state={...state,...e};for(const e of subscribers)e()};let config=null,channelsReady=Promise.resolve(),tokenSubscription=null,actionHandler=null;const receiveHandlers=new Set;let listening=!1,listeningForReceived=!1;const pendingResponses=[],routedAt=new Map,REPEAT_WINDOW_MS=1e4,requireConfig=()=>{if(!config)throw new Error("[@webority/mobile-core] call initPush before enablePush or disablePush.");return config},toPermissionStatus=e=>e.granted?"granted":"denied"===e.status?e.canAskAgain?"denied":"blocked":"undetermined",toStringData=e=>{const t={};for(const[n,o]of Object.entries(e??{}))null!=o&&(t[n]="object"==typeof o?JSON.stringify(o):String(o));return t},contentData=e=>{const t=e.request.content;if(t.data)return toStringData(t.data);if("string"==typeof t.dataString)try{return toStringData(JSON.parse(t.dataString))}catch(e){_index.Logger.error("[push] notification data is not JSON",e)}return{}},triggerData=e=>{const t=e.request.trigger,n={...t?.remoteMessage?.data??{}};for(const[e,o]of Object.entries(t?.payload??{}))"aps"===e||"body"===e&&"object"==typeof o||(n[e]=o);return toStringData(n)},notificationData=e=>({...triggerData(e),...contentData(e)}),responseData=e=>notificationData(e.notification),toPushReceived=e=>({notificationId:e.request.identifier,title:e.request.content.title??null,body:e.request.content.body??null,data:notificationData(e)});exports.toPushReceived=toPushReceived;const toPushAction=e=>({actionId:e.actionIdentifier,...e.userText?{userText:e.userText}:{},data:responseData(e),notificationId:e.notification.request.identifier});exports.toPushAction=toPushAction;const toNotificationActions=e=>e.map(e=>({identifier:e.id,buttonTitle:e.title,...e.textInput?{textInput:{submitButtonTitle:e.textInput.submitTitle,placeholder:e.textInput.placeholder}}:{},options:{opensAppToForeground:e.opensApp??!0,isDestructive:e.destructive??!1,isAuthenticationRequired:e.authenticationRequired??!1}}));exports.toNotificationActions=toNotificationActions;const routeResponse=async(e,t)=>{const n=`${t.notification.request.identifier}:${t.actionIdentifier}`,o=routedAt.get(n);if(void 0!==o&&Date.now()-o<1e4)return;if(t.actionIdentifier!==e.DEFAULT_ACTION_IDENTIFIER&&actionHandler){routedAt.set(n,Date.now());try{await actionHandler(toPushAction(t))}catch(e){_index.Logger.error("[push] onAction threw",e)}}else if(config){routedAt.set(n,Date.now());try{config.onOpen(responseData(t))}catch(e){_index.Logger.error("[push] onOpen threw",e)}}else pendingResponses.push(t)},drainPending=async e=>{const t=pendingResponses.splice(0);for(const n of t)await routeResponse(e,n)},listenForResponses=e=>{listening||(listening=!0,e.addNotificationResponseReceivedListener(t=>{routeResponse(e,t)}),e.getLastNotificationResponseAsync().then(async t=>(t&&await routeResponse(e,t),e.clearLastNotificationResponseAsync?.())).catch(e=>_index.Logger.error("[push] reading the launch notification failed",e)))},routeTaskPayload=async e=>{const t=resolveModules(),n=e;t&&"string"==typeof n?.actionIdentifier&&"string"==typeof n.notification?.request?.identifier&&await routeResponse(t.notifications,n)};exports.routeTaskPayload=routeTaskPayload;const createChannels=async(e,t)=>{for(const n of t)try{await e.setNotificationChannelAsync(n.id,{name:n.name,importance:"high"===n.importance?e.AndroidImportance.HIGH:e.AndroidImportance.DEFAULT})}catch(e){_index.Logger.error(`[push] creating channel ${n.id} failed`,e)}},APNS_ENVIRONMENTS={development:"Development",production:"Production"},readApnsEnvironment=async e=>{try{return APNS_ENVIRONMENTS[await e.getApnsEnvironment()??""]??null}catch(e){return _index.Logger.warn("[push] reading the APNs environment failed",e),null}},deviceTimeZone=()=>Intl.DateTimeFormat().resolvedOptions().timeZone||null,toDevice=async(e,t)=>{const n="android"===e.type?"Fcm":"ios"===e.type?"Apns":null;if(!n||"string"!=typeof e.data)return null;if(!t.applicationId)throw new Error("[@webority/mobile-core] push needs the app bundle id from expo-application.");return{installationId:await requireConfig().getInstallationId(),platform:n,token:e.data,appId:t.applicationId,apnsEnvironment:"Apns"===n?await readApnsEnvironment(t):null,timeZone:deviceTimeZone()}},initPush=e=>{const t=null===config;if(config=e,!t)return;const n=resolveModules();if(!n)return void setState({status:"unavailable"});const o=n.notifications;o.setNotificationHandler({handleNotification:async()=>{const e=config?.showInForeground?.()??!0;return{shouldShowBanner:e,shouldShowList:e,shouldPlaySound:e&&(config?.playSoundInForeground?.()??!0),shouldSetBadge:!0}}}),"android"===_reactNative.Platform.OS&&e.androidChannels?.length&&(channelsReady=createChannels(o,e.androidChannels)),listenForResponses(o),drainPending(o),o.getPermissionsAsync().then(e=>setState({status:toPermissionStatus(e)})).catch(e=>_index.Logger.error("[push] permission check failed",e))};exports.initPush=initPush;let registering=null,registeredKey=null,unregistering=null,tokenDrop=Promise.resolve();const registerOnce=e=>{const t=JSON.stringify(e);if(registering?.key===t)return registering.promise;const n=requireConfig().register(e).then(()=>{registeredKey=t}).finally(()=>{registering?.promise===n&&(registering=null)});return registering={key:t,promise:n},n},enablePush=async({prompt:e=!0}={})=>{requireConfig();const t=resolveModules();if(!t)return setState({status:"unavailable"}),"unavailable";const n=t.notifications;await channelsReady,await tokenDrop;let o=await n.getPermissionsAsync();if(!o.granted&&e&&(o=await n.requestPermissionsAsync()),!o.granted){const e=toPermissionStatus(o);return setState({status:e}),e}const i=await toDevice(await n.getDevicePushTokenAsync(),t);return i?(await registerOnce(i),tokenSubscription?.remove(),tokenSubscription=n.addPushTokenListener(e=>{(unregistering??Promise.resolve()).then(()=>state.enabled?toDevice(e,t):null).then(e=>e&&JSON.stringify(e)!==registeredKey?registerOnce(e):void 0).catch(e=>_index.Logger.error("[push] re-registering a new token failed",e))}),setState({status:"granted",enabled:!0}),"granted"):(setState({status:"unavailable"}),"unavailable")};exports.enablePush=enablePush;const readDevicePushToken=async()=>{const e=resolveModules();if(!e)return null;await tokenDrop;if(!(await e.notifications.getPermissionsAsync()).granted)return null;const t=await e.notifications.getDevicePushTokenAsync(),n="android"===t.type?"android":"ios"===t.type?"ios":null;return n&&"string"==typeof t.data?{platform:n,token:t.data}:null};exports.readDevicePushToken=readDevicePushToken;const stopFollowingToken=()=>{tokenSubscription?.remove(),tokenSubscription=null,registeredKey=null,setState({enabled:!1})},disablePush=async()=>{const e=requireConfig(),t=await e.getInstallationId();await(registering?.promise.catch(()=>{}));let settle=()=>{};const n=new Promise(e=>{settle=e});unregistering=n;try{await e.unregister(t),stopFollowingToken()}finally{unregistering===n&&(unregistering=null),settle()}};exports.disablePush=disablePush;const resetPush=async()=>{stopFollowingToken();const e=resolveModules();if(!e)return;const t=e.notifications.unregisterForNotificationsAsync();tokenDrop=t.catch(()=>{}),await t};exports.resetPush=resetPush;const setBadgeCount=async e=>{const t=resolveModules();t&&await t.notifications.setBadgeCountAsync(e)};exports.setBadgeCount=setBadgeCount;const dismissAllNotifications=async()=>{const e=resolveModules();if(e)try{await e.notifications.dismissAllNotificationsAsync()}catch(e){_index.Logger.warn("[push] dismissing the notifications failed",e)}};exports.dismissAllNotifications=dismissAllNotifications;const setCategories=async e=>{const t=resolveModules();if(t)for(const n of e)await t.notifications.setNotificationCategoryAsync(n.id,toNotificationActions(n.actions))};exports.setCategories=setCategories;const onAction=e=>{actionHandler=e;const t=resolveModules();return t&&(listenForResponses(t.notifications),drainPending(t.notifications)),()=>{actionHandler===e&&(actionHandler=null)}};exports.onAction=onAction;const onReceive=e=>{receiveHandlers.add(e);const t=resolveModules();return t&&!listeningForReceived&&(listeningForReceived=!0,t.notifications.addNotificationReceivedListener(e=>{const t=toPushReceived(e);for(const e of[...receiveHandlers])try{e(t)}catch(e){_index.Logger.error("[push] onReceive threw",e)}})),()=>{receiveHandlers.delete(e)}};exports.onReceive=onReceive;const notifyLocal=async({title:e,body:t,data:n})=>{const o=resolveModules();o&&await o.notifications.scheduleNotificationAsync({content:{title:e,body:t,data:n??{}},trigger:null})};exports.notifyLocal=notifyLocal;const subscribe=e=>(subscribers.add(e),()=>{subscribers.delete(e)}),getSnapshot=()=>state,enable=async()=>{await enablePush()},usePush=()=>({...(0,_react.useSyncExternalStore)(subscribe,getSnapshot,getSnapshot),enable:enable,disable:disablePush});exports.usePush=usePush;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.usePush=exports.toPushReceived=exports.toPushAction=exports.toNotificationActions=exports.setPushImplementation=exports.setCategories=exports.setBadgeCount=exports.routeTaskPayload=exports.resolveModules=exports.resetPush=exports.readDevicePushToken=exports.onReceive=exports.onAction=exports.notifyLocal=exports.initPush=exports.enablePush=exports.dismissAllNotifications=exports.disablePush=void 0;var _react=require("react"),_reactNative=require("react-native"),_index=require("../logger/index.js");let resolved,override=null;const setPushImplementation=e=>{override=e};exports.setPushImplementation=setPushImplementation;const resolveModules=()=>{if(override)return override;if(void 0!==resolved)return resolved;try{if(require("expo").isRunningInExpoGo())return resolved=null,resolved;const e=require("expo-notifications"),t=require("expo-application");resolved={notifications:e,applicationId:t.applicationId,getApnsEnvironment:()=>t.getIosPushNotificationServiceEnvironmentAsync()}}catch(e){_index.Logger.warn("[push] expo-notifications is not available; push is off",e),resolved=null}return resolved};exports.resolveModules=resolveModules;let state={status:"unknown",enabled:!1,registrationError:null};const subscribers=new Set,setState=e=>{state={...state,...e};for(const e of subscribers)e()};let config=null,channelsReady=Promise.resolve(),tokenSubscription=null,actionHandler=null;const receiveHandlers=new Set;let listening=!1,listeningForReceived=!1;const pendingResponses=[],routedAt=new Map,REPEAT_WINDOW_MS=1e4,requireConfig=()=>{if(!config)throw new Error("[@webority/mobile-core] call initPush before enablePush or disablePush.");return config},toPermissionStatus=e=>e.granted?"granted":"denied"===e.status?e.canAskAgain?"denied":"blocked":"undetermined",toStringData=e=>{const t={};for(const[n,o]of Object.entries(e??{}))null!=o&&(t[n]="object"==typeof o?JSON.stringify(o):String(o));return t},contentData=e=>{const t=e.request.content;if(t.data)return toStringData(t.data);if("string"==typeof t.dataString)try{return toStringData(JSON.parse(t.dataString))}catch(e){_index.Logger.error("[push] notification data is not JSON",e)}return{}},triggerData=e=>{const t=e.request.trigger,n={...t?.remoteMessage?.data??{}};for(const[e,o]of Object.entries(t?.payload??{}))"aps"===e||"body"===e&&"object"==typeof o||(n[e]=o);return toStringData(n)},notificationData=e=>({...triggerData(e),...contentData(e)}),responseData=e=>notificationData(e.notification),toPushReceived=e=>({notificationId:e.request.identifier,title:e.request.content.title??null,body:e.request.content.body??null,data:notificationData(e)});exports.toPushReceived=toPushReceived;const toPushAction=e=>({actionId:e.actionIdentifier,...e.userText?{userText:e.userText}:{},data:responseData(e),notificationId:e.notification.request.identifier});exports.toPushAction=toPushAction;const toNotificationActions=e=>e.map(e=>({identifier:e.id,buttonTitle:e.title,...e.textInput?{textInput:{submitButtonTitle:e.textInput.submitTitle,placeholder:e.textInput.placeholder}}:{},options:{opensAppToForeground:e.opensApp??!0,isDestructive:e.destructive??!1,isAuthenticationRequired:e.authenticationRequired??!1}}));exports.toNotificationActions=toNotificationActions;const routeResponse=async(e,t)=>{const n=`${t.notification.request.identifier}:${t.actionIdentifier}`,o=routedAt.get(n);if(void 0!==o&&Date.now()-o<1e4)return;if(t.actionIdentifier!==e.DEFAULT_ACTION_IDENTIFIER&&actionHandler){routedAt.set(n,Date.now());try{await actionHandler(toPushAction(t))}catch(e){_index.Logger.error("[push] onAction threw",e)}}else if(config){routedAt.set(n,Date.now());try{config.onOpen(responseData(t))}catch(e){_index.Logger.error("[push] onOpen threw",e)}}else pendingResponses.push(t)},drainPending=async e=>{const t=pendingResponses.splice(0);for(const n of t)await routeResponse(e,n)},listenForResponses=e=>{listening||(listening=!0,e.addNotificationResponseReceivedListener(t=>{routeResponse(e,t)}),e.getLastNotificationResponseAsync().then(async t=>(t&&await routeResponse(e,t),e.clearLastNotificationResponseAsync?.())).catch(e=>_index.Logger.error("[push] reading the launch notification failed",e)))},routeTaskPayload=async e=>{const t=resolveModules(),n=e;t&&"string"==typeof n?.actionIdentifier&&"string"==typeof n.notification?.request?.identifier&&await routeResponse(t.notifications,n)};exports.routeTaskPayload=routeTaskPayload;const createChannels=async(e,t)=>{for(const n of t)try{await e.setNotificationChannelAsync(n.id,{name:n.name,importance:"high"===n.importance?e.AndroidImportance.HIGH:e.AndroidImportance.DEFAULT})}catch(e){_index.Logger.error(`[push] creating channel ${n.id} failed`,e)}},APNS_ENVIRONMENTS={development:"Development",production:"Production"},readApnsEnvironment=async e=>{try{return APNS_ENVIRONMENTS[await e.getApnsEnvironment()??""]??null}catch(e){return _index.Logger.warn("[push] reading the APNs environment failed",e),null}},deviceTimeZone=()=>Intl.DateTimeFormat().resolvedOptions().timeZone||null,toDevice=async(e,t)=>{const n="android"===e.type?"Fcm":"ios"===e.type?"Apns":null;if(!n||"string"!=typeof e.data)return null;if(!t.applicationId)throw new Error("[@webority/mobile-core] push needs the app bundle id from expo-application.");return{installationId:await requireConfig().getInstallationId(),platform:n,token:e.data,appId:t.applicationId,apnsEnvironment:"Apns"===n?await readApnsEnvironment(t):null,timeZone:deviceTimeZone()}},initPush=e=>{const t=null===config;if(config=e,!t)return;const n=resolveModules();if(!n)return void setState({status:"unavailable"});const o=n.notifications;o.setNotificationHandler({handleNotification:async()=>{const e=config?.showInForeground?.()??!0;return{shouldShowBanner:e,shouldShowList:e,shouldPlaySound:e&&(config?.playSoundInForeground?.()??!0),shouldSetBadge:!0}}}),"android"===_reactNative.Platform.OS&&e.androidChannels?.length&&(channelsReady=createChannels(o,e.androidChannels)),listenForResponses(o),drainPending(o),o.getPermissionsAsync().then(e=>setState({status:toPermissionStatus(e)})).catch(e=>_index.Logger.error("[push] permission check failed",e))};exports.initPush=initPush;let registering=null,registeredKey=null,unregistering=null,tokenDrop=Promise.resolve();const registerOnce=e=>{const t=JSON.stringify(e);if(registering?.key===t)return registering.promise;const n=requireConfig().register(e).then(()=>{registeredKey=t,state.registrationError&&setState({registrationError:null})}).finally(()=>{registering?.promise===n&&(registering=null)});return registering={key:t,promise:n},n},enablePush=async({prompt:e=!0}={})=>{requireConfig();const t=resolveModules();if(!t)return setState({status:"unavailable"}),"unavailable";const n=t.notifications;await channelsReady,await tokenDrop;let o=await n.getPermissionsAsync();if(!o.granted&&e&&(o=await n.requestPermissionsAsync()),!o.granted){const e=toPermissionStatus(o);return setState({status:e}),e}const i=await toDevice(await n.getDevicePushTokenAsync(),t);return i?(await registerOnce(i),tokenSubscription?.remove(),tokenSubscription=n.addPushTokenListener(e=>{(unregistering??Promise.resolve()).then(()=>state.enabled?toDevice(e,t):null).then(e=>e&&JSON.stringify(e)!==registeredKey?registerOnce(e):void 0).catch(e=>{_index.Logger.error("[push] re-registering a new token failed",e),setState({registrationError:e instanceof Error?e:new Error(String(e))})})}),setState({status:"granted",enabled:!0}),"granted"):(setState({status:"unavailable"}),"unavailable")};exports.enablePush=enablePush;const readDevicePushToken=async()=>{const e=resolveModules();if(!e)return null;await tokenDrop;if(!(await e.notifications.getPermissionsAsync()).granted)return null;const t=await e.notifications.getDevicePushTokenAsync(),n="android"===t.type?"android":"ios"===t.type?"ios":null;return n&&"string"==typeof t.data?{platform:n,token:t.data}:null};exports.readDevicePushToken=readDevicePushToken;const stopFollowingToken=()=>{tokenSubscription?.remove(),tokenSubscription=null,registeredKey=null,setState({enabled:!1,registrationError:null})},disablePush=async()=>{const e=requireConfig(),t=await e.getInstallationId();await(registering?.promise.catch(()=>{}));let settle=()=>{};const n=new Promise(e=>{settle=e});unregistering=n;try{await e.unregister(t),stopFollowingToken()}finally{unregistering===n&&(unregistering=null),settle()}};exports.disablePush=disablePush;const resetPush=async()=>{stopFollowingToken();const e=resolveModules();if(!e)return;const t=e.notifications.unregisterForNotificationsAsync();tokenDrop=t.catch(()=>{}),await t};exports.resetPush=resetPush;const setBadgeCount=async e=>{const t=resolveModules();t&&await t.notifications.setBadgeCountAsync(e)};exports.setBadgeCount=setBadgeCount;const dismissAllNotifications=async()=>{const e=resolveModules();if(e)try{await e.notifications.dismissAllNotificationsAsync()}catch(e){_index.Logger.warn("[push] dismissing the notifications failed",e)}};exports.dismissAllNotifications=dismissAllNotifications;const setCategories=async e=>{const t=resolveModules();if(t)for(const n of e)await t.notifications.setNotificationCategoryAsync(n.id,toNotificationActions(n.actions))};exports.setCategories=setCategories;const onAction=e=>{actionHandler=e;const t=resolveModules();return t&&(listenForResponses(t.notifications),drainPending(t.notifications)),()=>{actionHandler===e&&(actionHandler=null)}};exports.onAction=onAction;const onReceive=e=>{receiveHandlers.add(e);const t=resolveModules();return t&&!listeningForReceived&&(listeningForReceived=!0,t.notifications.addNotificationReceivedListener(e=>{const t=toPushReceived(e);for(const e of[...receiveHandlers])try{e(t)}catch(e){_index.Logger.error("[push] onReceive threw",e)}})),()=>{receiveHandlers.delete(e)}};exports.onReceive=onReceive;const notifyLocal=async({title:e,body:t,data:n})=>{const o=resolveModules();o&&await o.notifications.scheduleNotificationAsync({content:{title:e,body:t,data:n??{}},trigger:null})};exports.notifyLocal=notifyLocal;const subscribe=e=>(subscribers.add(e),()=>{subscribers.delete(e)}),getSnapshot=()=>state,enable=async()=>{await enablePush()},usePush=()=>({...(0,_react.useSyncExternalStore)(subscribe,getSnapshot,getSnapshot),enable:enable,disable:disablePush});exports.usePush=usePush;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.useSecureScreen=void 0;var _react=require("react"),_reactNative=require("react-native"),_index=require("../logger/index.js");const screenCapture=()=>require("expo-screen-capture"),report=e=>r=>{_index.Logger.error(`[@webority/mobile-core] useSecureScreen could not ${e}.`,r)};let nextKey=0,appSwitcherHolders=0;const useSecureScreen=(e={})=>{const{focused:r=!0}=e,t=(0,_react.useRef)(null);null===t.current&&(nextKey+=1,t.current=`webority-secure-screen-${nextKey}`),(0,_react.useEffect)(()=>{if(!r)return;const e=t.current,c=screenCapture();c.preventScreenCaptureAsync(e).catch(
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.useSecureScreen=void 0;var _react=require("react"),_reactNative=require("react-native"),_index=require("../logger/index.js");const screenCapture=()=>require("expo-screen-capture"),report=e=>r=>{_index.Logger.error(`[@webority/mobile-core] useSecureScreen could not ${e}.`,r)},protectionFailed=(e,r)=>t=>{report(e)(t),r(new Error(`[@webority/mobile-core] useSecureScreen could not ${e}, so the screen is not protected.`,{cause:t}))};let nextKey=0,appSwitcherHolders=0;const useSecureScreen=(e={})=>{const{focused:r=!0}=e,t=(0,_react.useRef)(null);null===t.current&&(nextKey+=1,t.current=`webority-secure-screen-${nextKey}`);const[c,o]=(0,_react.useState)(null);if((0,_react.useEffect)(()=>{if(!r)return;const e=t.current,c=screenCapture();c.preventScreenCaptureAsync(e).catch(protectionFailed("block screen capture",o));const n="ios"===_reactNative.Platform.OS;return n&&(appSwitcherHolders+=1,1===appSwitcherHolders&&c.enableAppSwitcherProtectionAsync().catch(protectionFailed("hide the app switcher snapshot",o))),()=>{c.allowScreenCaptureAsync(e).catch(report("release screen capture")),n&&(appSwitcherHolders-=1,0===appSwitcherHolders&&c.disableAppSwitcherProtectionAsync().catch(report("restore the app switcher snapshot")))}},[r]),c)throw c};exports.useSecureScreen=useSecureScreen;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.setSmsRetrieverImplementation=exports.SmsRetriever=void 0;var _reactNative=require("react-native"),_index=require("../logger/index.js");const OTP_EVENT="WeborityMobileCoreSmsRetrieved",ERROR_EVENT="WeborityMobileCoreSmsRetrieverError";let backend=null;const setSmsRetrieverImplementation=e=>{backend=e};let nativeModule;exports.setSmsRetrieverImplementation=setSmsRetrieverImplementation;const resolveNativeModule=()=>{if(void 0!==nativeModule)return nativeModule;if("android"!==_reactNative.Platform.OS)return nativeModule=null,null;try{nativeModule=require("../specs/NativeSmsRetriever").default??null}catch(e){_index.Logger.warn("[smsRetriever] native module not available",e),nativeModule=null}return nativeModule??null},defaultBackend={getAppHash:async()=>{const e=resolveNativeModule();if(!e)throw new Error("[smsRetriever] getAppHash: native module unavailable (Android only).");return e.getAppHash()},startListening:(e,t)=>{const r=resolveNativeModule();if(!r)return t?.({type:"SERVICE_UNAVAILABLE",message:"SMS Retriever is Android-only, or the native module is not linked."}),{remove:()=>{}};const i=_reactNative.DeviceEventEmitter.addListener(OTP_EVENT,t=>e(t.message)),n=t?_reactNative.DeviceEventEmitter.addListener(ERROR_EVENT,e=>t(e)):null;try{r.startSMSListener()}catch(e){
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.setSmsRetrieverImplementation=exports.SmsRetriever=void 0;var _reactNative=require("react-native"),_index=require("../logger/index.js");const OTP_EVENT="WeborityMobileCoreSmsRetrieved",ERROR_EVENT="WeborityMobileCoreSmsRetrieverError";let backend=null;const setSmsRetrieverImplementation=e=>{backend=e};let nativeModule;exports.setSmsRetrieverImplementation=setSmsRetrieverImplementation;const resolveNativeModule=()=>{if(void 0!==nativeModule)return nativeModule;if("android"!==_reactNative.Platform.OS)return nativeModule=null,null;try{nativeModule=require("../specs/NativeSmsRetriever").default??null}catch(e){_index.Logger.warn("[smsRetriever] native module not available",e),nativeModule=null}return nativeModule??null},defaultBackend={getAppHash:async()=>{const e=resolveNativeModule();if(!e)throw new Error("[smsRetriever] getAppHash: native module unavailable (Android only).");return e.getAppHash()},startListening:(e,t)=>{const r=resolveNativeModule();if(!r)return t?.({type:"SERVICE_UNAVAILABLE",message:"SMS Retriever is Android-only, or the native module is not linked."}),{remove:()=>{}};const i=_reactNative.DeviceEventEmitter.addListener(OTP_EVENT,t=>e(t.message)),n=t?_reactNative.DeviceEventEmitter.addListener(ERROR_EVENT,e=>t(e)):null;try{r.startSMSListener()}catch(e){if(i.remove(),n?.remove(),!t)throw e;return t({type:"UNKNOWN_ERROR",message:e instanceof Error?e.message:String(e)}),{remove:()=>{}}}return{remove:()=>{i.remove(),n?.remove();try{r.stopSMSListener()}catch(e){_index.Logger.error("[smsRetriever] stopSMSListener failed",e)}}}}},SmsRetriever=exports.SmsRetriever={isAvailable:()=>null!==resolveNativeModule(),getAppHash:()=>(backend??defaultBackend).getAppHash(),startListening:(e,t)=>(backend??defaultBackend).startListening(e,t)};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.useOtaUpdates=exports.stopOtaUpdates=exports.setOtaUpdatesImplementation=exports.normalizeAppIdentity=exports.initOtaUpdates=exports.checkForOtaUpdate=exports.applyOtaUpdate=exports.OTA_LAST_LAUNCH_KEY=exports.DEFAULT_MIN_CHECK_INTERVAL_MS=void 0;var _react=require("react"),_reactNative=require("react-native"),_index=require("../config/index.js"),_appIdentity=require("../config/appIdentity.js"),_index2=require("../logger/index.js"),_index3=require("../storage/index.js");const PREFIX="[@webority/mobile-core] OTA updates:",REPORTED_KEY="@webority/ota/last-reported-update-id",OTA_LAST_LAUNCH_KEY=exports.OTA_LAST_LAUNCH_KEY="@webority/ota/last-launch",ENV_IDENTITY_SUFFIXES=Object.values(_appIdentity.ENVIRONMENT_APP_ID_SUFFIX).filter(e=>""!==e),DEFAULT_MIN_CHECK_INTERVAL_MS=exports.DEFAULT_MIN_CHECK_INTERVAL_MS=9e5,EVENT_TIMEOUT_MS=1e4;let resolved,override=null;const setOtaUpdatesImplementation=e=>{override=e};exports.setOtaUpdatesImplementation=setOtaUpdatesImplementation;const resolveUpdates=()=>{if(override)return override;if(void 0!==resolved)return resolved;try{resolved=require("expo-updates")}catch{resolved=null}return resolved},INITIAL_STATE={status:"unavailable",runningUpdateId:null,error:null,lastCheckedAt:null};let state=INITIAL_STATE;const subscribers=new Set,setState=e=>{state={...state,...e};for(const e of subscribers)e()};let config=null,stateSubscription=null,appStateSubscription=null,checking=null,lastCheckStartedAt=0,lastReportedError=null;const messageOf=e=>e instanceof Error?e.message:String(e),normalizeAppIdentity=e=>{const t=String(e??"").trim().toLowerCase(),a=ENV_IDENTITY_SUFFIXES.find(e=>t.endsWith(e));return a?t.slice(0,-a.length):t};exports.normalizeAppIdentity=normalizeAppIdentity;const ownIdentity=()=>config?.appIdentifier??(0,_index.getConfigValue)("appId",null)??null,identityMismatch=e=>{const t=e?.extra?.webority?.appIdentifier;if(!t)return null;const a=ownIdentity();return a&&normalizeAppIdentity(t)===normalizeAppIdentity(a)?null:`identity mismatch: the update is for '${t}' but this app is '${a??"unset"}'`},postEvent=async(e,t,a)=>{const r=config?.serverUrl;if(!r||!e)return;const n=new AbortController,s=setTimeout(()=>n.abort(),1e4);try{await fetch(`${r.replace(/\/+$/,"")}/ota/updates/${encodeURIComponent(e)}/events`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:t,platform:_reactNative.Platform.OS,runtimeVersion:resolveUpdates()?.runtimeVersion??null,message:a}),signal:n.signal})}catch(e){_index2.Logger.info(`${PREFIX} the ${t} event was not reported: ${messageOf(e)}`)}finally{clearTimeout(s)}},reportError=(e,t)=>{setState({status:"error",error:t});const a=`${e??""}|${t}`;a!==lastReportedError&&(lastReportedError=a,_index2.Logger.error(`${PREFIX} ${t}`),postEvent(e,"error",t))},recordLaunch=async e=>{const t={updateId:e.updateId,channel:e.channel??null,runtimeVersion:e.runtimeVersion,isEmbeddedLaunch:e.isEmbeddedLaunch,isEmergencyLaunch:e.isEmergencyLaunch??!1,emergencyLaunchReason:e.emergencyLaunchReason??null,launchedAtUtc:(new Date).toISOString()};await _index3.Storage.setItem(OTA_LAST_LAUNCH_KEY,JSON.stringify(t))||_index2.Logger.error(`${PREFIX} the launch record was not saved`)},reportRunningUpdate=async e=>{if(await recordLaunch(e),e.isEmbeddedLaunch||!e.updateId)return;const t=identityMismatch(e.manifest);t?reportError(e.updateId,t):await _index3.Storage.getItem(REPORTED_KEY)!==e.updateId&&(await postEvent(e.updateId,"success"),await _index3.Storage.setItem(REPORTED_KEY,e.updateId),_index2.Logger.info(`${PREFIX} running update ${e.updateId}`))},onStateChange=e=>{const t=e.downloadError??e.checkError;if(t){const a=e.latestManifest?.id??resolveUpdates()?.updateId;return void reportError(a,t.message)}e.isChecking?setState({status:"checking"}):e.isDownloading?setState({status:"downloading"}):e.isUpdatePending&&setState({status:"ready",error:null})},checkForOtaUpdate=()=>{const e=resolveUpdates();if(!config||!e?.isEnabled)return Promise.resolve("unavailable");if(checking)return checking;lastCheckStartedAt=Date.now();return checking=(async()=>{try{setState({status:"checking"});const t=await e.checkForUpdateAsync();if(t.isAvailable){const e=identityMismatch(t.manifest);if(e)return reportError(t.manifest?.id,e),"error"}return t.isAvailable||t.isRollBackToEmbedded?(setState({status:"downloading"}),await e.fetchUpdateAsync(),setState({status:"ready",error:null}),"ready"):(setState({status:"ready"===state.status?"ready":"idle",error:null}),state.status)}catch(t){return reportError(e.updateId,messageOf(t)),"error"}finally{setState({lastCheckedAt:Date.now()}),checking=null}})(),checking};exports.checkForOtaUpdate=checkForOtaUpdate;const onAppStateChange=e=>{if("active"!==e||!1===config?.checkOnForeground)return;const t=config?.minCheckIntervalMs??DEFAULT_MIN_CHECK_INTERVAL_MS;Date.now()-lastCheckStartedAt<t||checkForOtaUpdate()},initOtaUpdates=e=>{const t=null===config;if(config=e,!t)return;const a=resolveUpdates();if(!a?.isEnabled)return void setState({status:"unavailable"});setState({status:"idle",runningUpdateId:a.isEmbeddedLaunch?null:a.updateId}),reportRunningUpdate(a).catch(e=>{_index2.Logger.info(`${PREFIX} start-up report failed: ${messageOf(e)}`)}),"function"==typeof a.addUpdatesStateChangeListener&&(stateSubscription=a.addUpdatesStateChangeListener(e=>onStateChange(e.context))),appStateSubscription=_reactNative.AppState.addEventListener("change",onAppStateChange);"ON_LOAD"===a.checkAutomatically||"WIFI_ONLY"===a.checkAutomatically||checkForOtaUpdate()};exports.initOtaUpdates=initOtaUpdates;const applyOtaUpdate=async()=>{const e=resolveUpdates();e?.isEnabled&&"ready"===state.status&&await e.reloadAsync()};exports.applyOtaUpdate=applyOtaUpdate;const stopOtaUpdates=()=>{stateSubscription?.remove(),appStateSubscription?.remove(),stateSubscription=null,appStateSubscription=null,config=null,checking=null,lastCheckStartedAt=0,lastReportedError=null,resolved=void 0,setState(INITIAL_STATE)};exports.stopOtaUpdates=stopOtaUpdates;const subscribe=e=>(subscribers.add(e),()=>{subscribers.delete(e)}),getSnapshot=()=>state,useOtaUpdates=()=>({...(0,_react.useSyncExternalStore)(subscribe,getSnapshot,getSnapshot),check:checkForOtaUpdate,apply:applyOtaUpdate});exports.useOtaUpdates=useOtaUpdates;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.useOtaUpdates=exports.stopOtaUpdates=exports.setOtaUpdatesImplementation=exports.normalizeAppIdentity=exports.initOtaUpdates=exports.checkForOtaUpdate=exports.applyOtaUpdate=exports.OTA_LAST_LAUNCH_KEY=exports.DEFAULT_MIN_CHECK_INTERVAL_MS=void 0;var _react=require("react"),_reactNative=require("react-native"),_index=require("../config/index.js"),_appIdentity=require("../config/appIdentity.js"),_index2=require("../logger/index.js"),_index3=require("../storage/index.js");const PREFIX="[@webority/mobile-core] OTA updates:",REPORTED_KEY="@webority/ota/last-reported-update-id",OTA_LAST_LAUNCH_KEY=exports.OTA_LAST_LAUNCH_KEY="@webority/ota/last-launch",ENV_IDENTITY_SUFFIXES=Object.values(_appIdentity.ENVIRONMENT_APP_ID_SUFFIX).filter(e=>""!==e),DEFAULT_MIN_CHECK_INTERVAL_MS=exports.DEFAULT_MIN_CHECK_INTERVAL_MS=9e5,EVENT_TIMEOUT_MS=1e4;let resolved,override=null;const setOtaUpdatesImplementation=e=>{override=e};exports.setOtaUpdatesImplementation=setOtaUpdatesImplementation;const resolveUpdates=()=>{if(__DEV__)return null;if(override)return override;if(void 0!==resolved)return resolved;try{resolved=require("expo-updates")}catch{resolved=null}return resolved},INITIAL_STATE={status:"unavailable",runningUpdateId:null,error:null,lastCheckedAt:null};let state=INITIAL_STATE;const subscribers=new Set,setState=e=>{state={...state,...e};for(const e of subscribers)e()};let config=null,stateSubscription=null,appStateSubscription=null,checking=null,lastCheckStartedAt=0,lastReportedError=null;const messageOf=e=>e instanceof Error?e.message:String(e),normalizeAppIdentity=e=>{const t=String(e??"").trim().toLowerCase(),a=ENV_IDENTITY_SUFFIXES.find(e=>t.endsWith(e));return a?t.slice(0,-a.length):t};exports.normalizeAppIdentity=normalizeAppIdentity;const ownIdentity=()=>config?.appIdentifier??(0,_index.getConfigValue)("appId",null)??null,identityMismatch=e=>{const t=e?.extra?.webority?.appIdentifier;if(!t)return null;const a=ownIdentity();return a&&normalizeAppIdentity(t)===normalizeAppIdentity(a)?null:`identity mismatch: the update is for '${t}' but this app is '${a??"unset"}'`},postEvent=async(e,t,a)=>{const r=config?.serverUrl;if(!r||!e)return;const n=new AbortController,s=setTimeout(()=>n.abort(),1e4);try{await fetch(`${r.replace(/\/+$/,"")}/ota/updates/${encodeURIComponent(e)}/events`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:t,platform:_reactNative.Platform.OS,runtimeVersion:resolveUpdates()?.runtimeVersion??null,message:a}),signal:n.signal})}catch(e){_index2.Logger.info(`${PREFIX} the ${t} event was not reported: ${messageOf(e)}`)}finally{clearTimeout(s)}},reportError=(e,t)=>{setState({status:"error",error:t});const a=`${e??""}|${t}`;a!==lastReportedError&&(lastReportedError=a,_index2.Logger.error(`${PREFIX} ${t}`),postEvent(e,"error",t))},recordLaunch=async e=>{const t={updateId:e.updateId,channel:e.channel??null,runtimeVersion:e.runtimeVersion,isEmbeddedLaunch:e.isEmbeddedLaunch,isEmergencyLaunch:e.isEmergencyLaunch??!1,emergencyLaunchReason:e.emergencyLaunchReason??null,launchedAtUtc:(new Date).toISOString()};await _index3.Storage.setItem(OTA_LAST_LAUNCH_KEY,JSON.stringify(t))||_index2.Logger.error(`${PREFIX} the launch record was not saved`)},reportRunningUpdate=async e=>{if(await recordLaunch(e),e.isEmbeddedLaunch||!e.updateId)return;const t=identityMismatch(e.manifest);t?reportError(e.updateId,t):await _index3.Storage.getItem(REPORTED_KEY)!==e.updateId&&(await postEvent(e.updateId,"success"),await _index3.Storage.setItem(REPORTED_KEY,e.updateId),_index2.Logger.info(`${PREFIX} running update ${e.updateId}`))},onStateChange=e=>{const t=e.downloadError??e.checkError;if(t){const a=e.latestManifest?.id??resolveUpdates()?.updateId;return void reportError(a,t.message)}e.isChecking?setState({status:"checking"}):e.isDownloading?setState({status:"downloading"}):e.isUpdatePending&&setState({status:"ready",error:null})},checkForOtaUpdate=()=>{const e=resolveUpdates();if(!config||!e?.isEnabled)return Promise.resolve("unavailable");if(checking)return checking;lastCheckStartedAt=Date.now();return checking=(async()=>{try{setState({status:"checking"});const t=await e.checkForUpdateAsync();if(t.isAvailable){const e=identityMismatch(t.manifest);if(e)return reportError(t.manifest?.id,e),"error"}return t.isAvailable||t.isRollBackToEmbedded?(setState({status:"downloading"}),await e.fetchUpdateAsync(),setState({status:"ready",error:null}),"ready"):(setState({status:"ready"===state.status?"ready":"idle",error:null}),state.status)}catch(t){return reportError(e.updateId,messageOf(t)),"error"}finally{setState({lastCheckedAt:Date.now()}),checking=null}})(),checking};exports.checkForOtaUpdate=checkForOtaUpdate;const onAppStateChange=e=>{if("active"!==e||!1===config?.checkOnForeground)return;const t=config?.minCheckIntervalMs??DEFAULT_MIN_CHECK_INTERVAL_MS;Date.now()-lastCheckStartedAt<t||checkForOtaUpdate()},initOtaUpdates=e=>{const t=null===config;if(config=e,!t)return;const a=resolveUpdates();if(!a?.isEnabled)return void setState({status:"unavailable"});setState({status:"idle",runningUpdateId:a.isEmbeddedLaunch?null:a.updateId}),reportRunningUpdate(a).catch(e=>{_index2.Logger.info(`${PREFIX} start-up report failed: ${messageOf(e)}`)}),"function"==typeof a.addUpdatesStateChangeListener&&(stateSubscription=a.addUpdatesStateChangeListener(e=>onStateChange(e.context))),appStateSubscription=_reactNative.AppState.addEventListener("change",onAppStateChange);"ON_LOAD"===a.checkAutomatically||"WIFI_ONLY"===a.checkAutomatically||checkForOtaUpdate()};exports.initOtaUpdates=initOtaUpdates;const applyOtaUpdate=async()=>{const e=resolveUpdates();e?.isEnabled&&"ready"===state.status&&await e.reloadAsync()};exports.applyOtaUpdate=applyOtaUpdate;const stopOtaUpdates=()=>{stateSubscription?.remove(),appStateSubscription?.remove(),stateSubscription=null,appStateSubscription=null,config=null,checking=null,lastCheckStartedAt=0,lastReportedError=null,resolved=void 0,setState(INITIAL_STATE)};exports.stopOtaUpdates=stopOtaUpdates;const subscribe=e=>(subscribers.add(e),()=>{subscribers.delete(e)}),getSnapshot=()=>state,useOtaUpdates=()=>({...(0,_react.useSyncExternalStore)(subscribe,getSnapshot,getSnapshot),check:checkForOtaUpdate,apply:applyOtaUpdate});exports.useOtaUpdates=useOtaUpdates;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{waitOrAbort}from"./retry.js";const
|
|
1
|
+
"use strict";import{IDEMPOTENCY_KEY_HEADER,isIdempotentMethod,isRetryableRequest,waitOrAbort}from"./retry.js";const DEFAULT_RETRIES=3,defaultDelayMs=e=>Math.random()*Math.min(2e3,500*2**(e-1)),retryAfterFrom=e=>{const t=Number(e.headers.get("retry-after"));return Number.isFinite(t)&&t>0?1e3*t:null},hasIdempotencyKey=e=>{const t=new Headers(e.headers).get(IDEMPOTENCY_KEY_HEADER);return null!==t&&""!==t};export const fetchWithRetry=async(e,t,r,s={})=>{const a=s.retries??3,o=s.retryDelayMs??defaultDelayMs,n=r.signal??void 0,i=!0===s.sideEffectFree||isIdempotentMethod(r.method??"GET"),y=hasIdempotencyKey(r);for(let s=0;;s++){let d,c;try{d=await e(t,r)}catch(e){if(!(e instanceof TypeError))throw e;c=e}const f=d?retryAfterFrom(d):null;if(!isRetryableRequest({idempotent:i,status:d?.status,namedWaitMs:f,hasIdempotencyKey:y})||s>=a||n?.aborted){if(d)return d;throw c}if(!await waitOrAbort(f??o(s+1),n)){if(d)return d;throw c}}};
|
package/lib/module/api/retry.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import axios from"axios";import{getConfigValue}from"../config/index.js";import{isWorkspaceChangedResponse}from"./workspace.js";export const IDEMPOTENCY_KEY_HEADER="Idempotency-Key";export const isRetryableStatus=e=>"number"==typeof e&&(429===e||e>=500&&e<=599);const IDEMPOTENT_METHODS=new Set(["get","head","options","put","delete"])
|
|
1
|
+
"use strict";import axios from"axios";import{getConfigValue}from"../config/index.js";import{isWorkspaceChangedResponse}from"./workspace.js";export const IDEMPOTENCY_KEY_HEADER="Idempotency-Key";export const isRetryableStatus=e=>"number"==typeof e&&(429===e||e>=500&&e<=599);const IDEMPOTENT_METHODS=new Set(["get","head","options","put","delete"]);export const isIdempotentMethod=e=>IDEMPOTENT_METHODS.has(e.toLowerCase());const NEVER_SENT_CODES=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN","ENETUNREACH","EHOSTUNREACH"]);export const isNeverSentError=e=>!e.response&&"string"==typeof e.code&&NEVER_SENT_CODES.has(e.code);const MAX_RETRY_AFTER_MS=3e4;export const retryAfterMs=e=>{const t=e.response;if(!t)return null;const r=t.headers,s="function"==typeof r?.get?r.get("retry-after"):r?.["retry-after"],o=Number(s);return null!=s&&Number.isFinite(o)&&o>0?1e3*o:null};const hasIdempotencyKey=e=>{const t=e?.headers,r="function"==typeof t?.get?t.get("Idempotency-Key"):t?.["Idempotency-Key"];return"string"==typeof r&&""!==r};export const isRetryableRequest=e=>void 0===e.status?e.idempotent:!!isRetryableStatus(e.status)&&(!(null!==e.namedWaitMs&&e.namedWaitMs>3e4)&&(e.idempotent||(429===e.status||503===e.status)&&e.hasIdempotencyKey));export const isRetryableFailure=e=>!axios.isCancel(e)&&"ERR_CANCELED"!==e.code&&(!!isNeverSentError(e)||isRetryableRequest({idempotent:isIdempotentMethod(e.config?.method??"get"),status:e.response?.status,namedWaitMs:retryAfterMs(e),hasIdempotencyKey:hasIdempotencyKey(e.config)}));export const resendWhenUnanswered={retries:1,shouldRetry:e=>isRetryableFailure(e)||!e.response&&!axios.isCancel(e)&&"ERR_CANCELED"!==e.code};const DEFAULT_POLICY={retryDelayMs:e=>Math.random()*Math.min(2e3,500*2**(e-1)),shouldRetry:isRetryableFailure,onRetry:()=>{}};export const waitOrAbort=(e,t)=>new Promise(r=>{const onAbort=()=>{clearTimeout(s),r(!1)},s=setTimeout(()=>{t?.removeEventListener?.("abort",onAbort),r(!0)},e);t?.addEventListener?.("abort",onAbort,{once:!0})});export const attachRetry=(e,t={})=>{e.interceptors.response.use(void 0,async r=>{const s=r,o=s?.config;if(!o||!1===o.retry||isWorkspaceChangedResponse(s))return Promise.reject(r);const n="object"==typeof o.retry?o.retry:{},a={...DEFAULT_POLICY,retries:getConfigValue("retries"),...t,...n},i=(o.__retryAttempt??0)+1;if(i>a.retries||!a.shouldRetry(s))return Promise.reject(r);if(o.signal?.aborted)return Promise.reject(r);o.__retryAttempt=i,1===i&&(o.__retryStartedAt=Date.now()),o.transformRequest=[e=>e];const c=retryAfterMs(s)??a.retryDelayMs(i),y=o.__retryStartedAt??Date.now();if(Date.now()-y+c>2e4)return Promise.reject(r);a.onRetry(i,s);return await waitOrAbort(c,o.signal)?e.request(o):Promise.reject(r)})};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import axios from"axios";import{ACCESS_TOKEN_KEY,clearSession,getToken,REFRESH_TOKEN_KEY,storeToken}from"../auth/authStore.js";import{Logger}from"../logger/index.js";import publicClient from"./publicClient.js";export const SESSION_REVOKED_CODE="session_revoked";export const SESSION_EXPIRED_CODE="session_expired";let store,auth;export const injectStore=e=>{store=e};export const injectUserAuth=e=>{auth=e};let refreshTokenPromise=null,failedQueue=[];const processQueue=(e,
|
|
1
|
+
"use strict";import axios from"axios";import{ACCESS_TOKEN_KEY,clearSession,getToken,REFRESH_TOKEN_KEY,storeToken}from"../auth/authStore.js";import{Logger}from"../logger/index.js";import publicClient from"./publicClient.js";export const SESSION_REVOKED_CODE="session_revoked";export const SESSION_EXPIRED_CODE="session_expired";export class SessionEndedError extends Error{constructor(e){super(e),this.name="SessionEndedError",Object.setPrototypeOf(this,SessionEndedError.prototype)}}let store,auth;export const injectStore=e=>{store=e};export const injectUserAuth=e=>{auth=e};let refreshTokenPromise=null,failedQueue=[];const processQueue=(e,s=null)=>{failedQueue.forEach(({resolve:r,reject:o})=>{e?o(e):null!==s&&r(s)}),failedQueue=[]};export const resetRefreshState=()=>{refreshTokenPromise=null,processQueue(new SessionEndedError("[@webority/mobile-core] Session ended"))};export const getErrorMessage=e=>e instanceof Error?e.message:"string"==typeof e?e:"Unknown error";const requireAuth=()=>{if(!store||!auth)throw new Error("User package store is not initialized. Call initUserAuth first.");return{store:store,auth:auth}};export const getAccountIdProvider=()=>auth?.accountId;export const getRefreshPath=()=>auth?.refresh.path;export const dispatchLogout=async()=>{const e=requireAuth();await e.store.dispatch(e.auth.logout())};export const endSessionAndLogout=async(e,s,r=null)=>{await clearSession(e,{code:s,detail:r}),await dispatchLogout()};export const sessionCodeOf=e=>{const s=e&&"object"==typeof e?e.code:void 0;return"session_revoked"===s||"session_expired"===s?s:null};export const sessionDetailOf=e=>{if(null===sessionCodeOf(e))return null;const s=e.detail;return"string"==typeof s&&""!==s?s:null};export const isRefreshInFlight=()=>null!==refreshTokenPromise;let replacementCount=0,replacementSettled=Promise.resolve(),settleReplacement=null;export const beginSessionReplacement=()=>{0===replacementCount&&(replacementSettled=new Promise(e=>{settleReplacement=e})),replacementCount+=1;let e=!1;return()=>{e||(e=!0,replacementCount-=1,0===replacementCount&&(settleReplacement?.(),settleReplacement=null))}};export const waitForSessionReplacement=()=>0===replacementCount?Promise.resolve():replacementSettled;export const currentTokenIfReplaced=async e=>{const s=(await getToken(ACCESS_TOKEN_KEY))?.token??null;return null!==s&&s!==e?s:null};export const queueBehindRefresh=()=>new Promise((e,s)=>{failedQueue.push({resolve:e,reject:s})});export const isSessionEnd=e=>e instanceof SessionEndedError||axios.isAxiosError(e)&&(400===e.response?.status||401===e.response?.status);const asString=(e,s)=>{if("string"!=typeof e||""===e)throw new Error(`The refresh response has no "${s}".`);return e},readWeborityTokens=e=>{const s=e??{};return{accessToken:asString(s.accessToken,"accessToken"),accessTokenExpiry:asString(s.accessTokenExpiration,"accessTokenExpiration"),refreshToken:asString(s.refreshToken,"refreshToken"),refreshTokenExpiry:asString(s.refreshTokenExpiration,"refreshTokenExpiration")}};class ReplacementTokensMissingError extends Error{constructor(e){super(`A session-replacing response carried no tokens: ${e}`),this.name="ReplacementTokensMissingError",Object.setPrototypeOf(this,ReplacementTokensMissingError.prototype)}}export const storeReplacementSession=async e=>{let s;try{s=(auth?.refresh.readTokens??readWeborityTokens)(e)}catch(e){throw new ReplacementTokensMissingError(getErrorMessage(e))}await storeToken(ACCESS_TOKEN_KEY,s.accessToken,s.accessTokenExpiry),await storeToken(REFRESH_TOKEN_KEY,s.refreshToken,s.refreshTokenExpiry)};const callRefreshEndpoint=async e=>{const s=await getToken(REFRESH_TOKEN_KEY);if(!s?.token)throw new SessionEndedError("No refresh token available");if(Date.parse(s.expiry)<=Date.now())throw new SessionEndedError("Refresh token expired");const r=await getToken(ACCESS_TOKEN_KEY),o={accessToken:r?.token??null,refreshToken:s.token},t=e.body?await e.body(o):o,n=e.headers?await e.headers():void 0;Logger.info("Refreshing the access token");const{data:i}=await publicClient.post(e.path,t,{...n?{headers:n}:{},skipErrorLog:!0}),a=(e.readTokens??readWeborityTokens)(i);if(await waitForSessionReplacement(),(await getToken(REFRESH_TOKEN_KEY))?.token!==s.token){const e=(await getToken(ACCESS_TOKEN_KEY))?.token;if(e)return Logger.info("Keeping the session that replaced this one during the refresh"),e}return await storeToken(ACCESS_TOKEN_KEY,a.accessToken,a.accessTokenExpiry),await storeToken(REFRESH_TOKEN_KEY,a.refreshToken,a.refreshTokenExpiry),Logger.info("Access token refreshed"),a.accessToken},endReason=e=>axios.isAxiosError(e)?sessionCodeOf(e.response?.data)??`status ${e.response?.status}`:getErrorMessage(e);export const refreshAccessToken=()=>{if(refreshTokenPromise)return refreshTokenPromise;const e=(async()=>{let e=null;try{const{refresh:s}=requireAuth().auth;e=(await getToken(ACCESS_TOKEN_KEY))?.token??null;const r=await callRefreshEndpoint(s);return processQueue(null,r),r}catch(s){if(isSessionEnd(s)){await waitForSessionReplacement();const s=await currentTokenIfReplaced(e);if(s)return Logger.info("The session was replaced during the refresh; continuing with the new one"),processQueue(null,s),s}const r=isSessionEnd(s);if(r)Logger.info("Session ended, the refresh was refused:",endReason(s));else{const e=axios.isAxiosError(s)?s.response?.data:void 0;Logger.error("Token refresh failed:",e??getErrorMessage(s))}if(processQueue(s,null),r){const e=axios.isAxiosError(s)&&401===s.response?.status,r=e?sessionCodeOf(s.response?.data):null,o=e?sessionDetailOf(s.response?.data):null;await endSessionAndLogout("rejected",r,o)}throw s}})().finally(()=>{refreshTokenPromise===e&&(refreshTokenPromise=null)});return refreshTokenPromise=e,e};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import axios,{AxiosHeaders}from"axios";import{ACCESS_TOKEN_KEY,getToken}from"../auth/authStore.js";import{getConfigValue}from"../config/index.js";import{Logger}from"../logger/index.js";import{getLastKnownNetworkStatus}from"../network/networkStatus.js";import"../types/axios.js";import{applyConfiguredBaseUrl}from"./baseUrl.js";import{applyClientHeaders,readAccountId,stampAccountId}from"./clientHeaders.js";import{logCurl}from"./curl.js";import{readMinAppVersion}from"./minAppVersion.js";import{sendFormDataAsMultipart}from"./multipart.js";import{applyRequestDefaults}from"./requestDefaults.js";import{responseBodyText}from"./responseBodyText.js";import{attachRetry}from"./retry.js";import{beginSessionReplacement,currentTokenIfReplaced,endSessionAndLogout,getAccountIdProvider,getErrorMessage,getRefreshPath,isRefreshInFlight,queueBehindRefresh,refreshAccessToken,resetRefreshState,sessionCodeOf,sessionDetailOf,storeReplacementSession,waitForSessionReplacement}from"./tokenRefresh.js";import{isWorkspaceChangedResponse,WorkspaceChangedError}from"./workspace.js";export{injectStore,injectUserAuth,resetRefreshState,SESSION_EXPIRED_CODE,SESSION_REVOKED_CODE}from"./tokenRefresh.js";export class RequestOfflineError extends Error{constructor(e="Request blocked: device is offline"){super(e),this.name="RequestOfflineError",Object.setPrototypeOf(this,RequestOfflineError.prototype)}}class NoAccessTokenError extends Error{constructor(){super("No access token available"),this.name="NoAccessTokenError",Object.setPrototypeOf(this,NoAccessTokenError.prototype)}}const endReplacement=e=>{e?._endReplacement?.(),e&&(e._endReplacement=void 0)},closeWindowIfTransformThrows=e=>{if(e._transformGuarded)return;e._transformGuarded=!0;const r=[].concat(e.transformRequest??[]);e.transformRequest=[function guarded(e,
|
|
1
|
+
"use strict";import axios,{AxiosHeaders}from"axios";import{ACCESS_TOKEN_KEY,getToken}from"../auth/authStore.js";import{getConfigValue}from"../config/index.js";import{Logger}from"../logger/index.js";import{getLastKnownNetworkStatus}from"../network/networkStatus.js";import"../types/axios.js";import{applyConfiguredBaseUrl}from"./baseUrl.js";import{applyClientHeaders,readAccountId,stampAccountId}from"./clientHeaders.js";import{logCurl}from"./curl.js";import{readMinAppVersion}from"./minAppVersion.js";import{sendFormDataAsMultipart}from"./multipart.js";import{applyRequestDefaults}from"./requestDefaults.js";import{responseBodyText}from"./responseBodyText.js";import{attachRetry}from"./retry.js";import{beginSessionReplacement,currentTokenIfReplaced,endSessionAndLogout,getAccountIdProvider,getErrorMessage,getRefreshPath,isRefreshInFlight,isSessionEnd,queueBehindRefresh,refreshAccessToken,resetRefreshState,SessionEndedError,sessionCodeOf,sessionDetailOf,storeReplacementSession,waitForSessionReplacement}from"./tokenRefresh.js";import{isWorkspaceChangedResponse,WorkspaceChangedError}from"./workspace.js";export{injectStore,injectUserAuth,resetRefreshState,SESSION_EXPIRED_CODE,SESSION_REVOKED_CODE}from"./tokenRefresh.js";export class RequestOfflineError extends Error{constructor(e="Request blocked: device is offline"){super(e),this.name="RequestOfflineError",Object.setPrototypeOf(this,RequestOfflineError.prototype)}}class NoAccessTokenError extends Error{constructor(){super("No access token available"),this.name="NoAccessTokenError",Object.setPrototypeOf(this,NoAccessTokenError.prototype)}}const endReplacement=e=>{e?._endReplacement?.(),e&&(e._endReplacement=void 0)},closeWindowIfTransformThrows=e=>{if(e._transformGuarded)return;e._transformGuarded=!0;const r=[].concat(e.transformRequest??[]);e.transformRequest=[function guarded(e,s){try{return r.reduce((e,r)=>r.call(this,e,s),e)}catch(e){throw endReplacement(this),e}}]},readSentToken=e=>{const r=e.headers instanceof AxiosHeaders?e.headers.get("Authorization"):void 0;return"string"==typeof r&&r.startsWith("Bearer ")?r.slice(7):null},userClient=axios.create({headers:{"Content-Type":"application/json"}});readMinAppVersion(userClient),attachRetry(userClient);const setAuthHeader=(e,r)=>{e.headers instanceof AxiosHeaders?e.headers.set("Authorization",`Bearer ${r}`):e.headers=AxiosHeaders.from({...e.headers,Authorization:`Bearer ${r}`})},isRefreshTokenRequest=e=>{const r=getRefreshPath();return!!r&&!!e?.includes(r)};userClient.interceptors.request.use(e=>{if(e.replacesSession&&!isRefreshTokenRequest(e.url)){const r=e;r._endReplacement=beginSessionReplacement(),closeWindowIfTransformThrows(r)}return e}),applyConfiguredBaseUrl(userClient),applyRequestDefaults(userClient),sendFormDataAsMultipart(userClient),userClient.interceptors.request.use(e=>(getConfigValue("logCurl")&&logCurl(e),e)),applyClientHeaders(userClient),userClient.interceptors.request.use(async e=>{endReplacement(e);if(!1===(await getLastKnownNetworkStatus()).isConnected)return Logger.warn(`Request blocked: device is offline. URL: ${e.url}`),Promise.reject(new RequestOfflineError);try{if(isRefreshTokenRequest(e.url))return e;await stampAccountId(e,getAccountIdProvider());const r=await getToken(ACCESS_TOKEN_KEY);if(!r?.token)throw new NoAccessTokenError;const s=Date.now(),t=Date.parse(r.expiry);if(t<=s+3e4){Logger.info("Access token expired or about to expire, refreshing before request");const r=await refreshAccessToken();setAuthHeader(e,r)}else setAuthHeader(e,r.token);return e}catch(r){return r instanceof NoAccessTokenError?Logger.info(`Request not sent: signed out. URL: ${e.url}`):isSessionEnd(r)||Logger.error("Failed to attach token:",getErrorMessage(r)),Promise.reject(r)}},e=>(Logger.error("Request error:",getErrorMessage(e)),Promise.reject(e))),userClient.interceptors.response.use(async e=>{const r=e.config;if(r._endReplacement)try{await storeReplacementSession(e.data)}finally{endReplacement(r)}return e},async e=>{if(endReplacement(e?.config),axios.isCancel(e))return Promise.reject(e);if(e instanceof RequestOfflineError||e instanceof NoAccessTokenError||e instanceof SessionEndedError)return Promise.reject(e);if(!axios.isAxiosError(e))return Logger.error(`Non-axios error in response interceptor: ${getErrorMessage(e)}`),Promise.reject(e);const r=e,s=r.config;if(!r.response)return s?.skipErrorLog||Logger.info(`Network error or no response from server: ${r.message}, URL: ${s?.url}`),Promise.reject(e);if(isWorkspaceChangedResponse(r))return Logger.info(`Refused for another workspace. URL: ${s?.url}`),Promise.reject(new WorkspaceChangedError("Refused for another workspace",{response:r.response,config:s,cause:e}));if(isRefreshTokenRequest(s?.url))return Promise.reject(e);if(401===r.response.status&&s&&!s._replayedWithCurrentToken&&!s.replacesSession&&(await waitForSessionReplacement(),await currentTokenIfReplaced(readSentToken(s)))){const r=await readAccountId(getAccountIdProvider());return(s._accountId??null)!==r?(Logger.info(`Workspace changed in flight; not sent again. URL: ${s.url}`),Promise.reject(new WorkspaceChangedError("Workspace changed in flight",{config:s,cause:e}))):(Logger.info(`Session changed while the request was in flight; sending it again. URL: ${s.url}`),s._replayedWithCurrentToken=!0,userClient(s))}if(401===r.response.status&&s&&!s._retry){const t=sessionCodeOf(r.response.data);if(null!==t)return Logger.warn(`Session ${t}, logging out without refresh. URL: ${s.url}`),resetRefreshState(),await endSessionAndLogout("terminated",t,sessionDetailOf(r.response.data)),Promise.reject(e);if(Logger.warn(`Unauthorized URL: ${s.url}`),s._retry=!0,isRefreshInFlight())return queueBehindRefresh().then(e=>(Logger.info("Retrying request after token refresh:",s.url),setAuthHeader(s,e),userClient(s))).catch(e=>(isSessionEnd(e)||Logger.error("Failed to retry request after token refresh:",getErrorMessage(e)),Promise.reject(e)));try{const e=await refreshAccessToken();return setAuthHeader(s,e),userClient(s)}catch(e){return Promise.reject(e)}}return s?.skipErrorLog||Logger.error(`Response error: ${responseBodyText(r.response?.data,r.message)}, URL: ${s?.url}, Status: ${r.response.status}`),Promise.reject(e)});export default userClient;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import*as SecureStore from"expo-secure-store";import{Logger}from"../logger/index.js";import{Storage}from"../storage/index.js";import{getJWTExpiry}from"./jwt.js";export const ACCESS_TOKEN_KEY="accessToken";export const REFRESH_TOKEN_KEY="refreshToken";export const SESSION_USER_KEY="sessionUser";export const LEGACY_REFRESH_TOKEN_LIFETIME_MS=2592e6;let backend=null;const keyFor=e=>(e??"default").replace(/[^A-Za-z0-9._-]/g,"_"),expoSecureStoreBackend={setGenericPassword:async(e,r,o)=>(await SecureStore.setItemAsync(keyFor(o?.service),JSON.stringify({username:e,password:r})),!0),getGenericPassword:async e=>{const r=e?.service,o=await SecureStore.getItemAsync(keyFor(r));if(null===o)return!1;const t=JSON.parse(o);return{username:t.username,password:t.password,service:r??"default"}},resetGenericPassword:async e=>(await SecureStore.deleteItemAsync(keyFor(e?.service)),!0)},resolveBackend=()=>backend??expoSecureStoreBackend,memo=new Map;let generation=0;const forget=e=>{generation+=1,void 0===e?memo.clear():memo.delete(e)},requireBackend=e=>{const r=resolveBackend();if(!r){const r=new Error(`[authStore] no secure-store backend available; cannot ${e}.`);throw Logger.error(r.message),r}return r};export const setKeychainImplementation=e=>{backend=e,forget()};export const storeToken=async(e,r,o)=>{Logger.info(`Storing token for key: ${e}`),forget(e);try{const t=JSON.stringify({token:r,expiry:o});await requireBackend("store a token").setGenericPassword("token",t,{service:e}),forget(e),memo.set(e,{token:r,expiry:o}),Logger.info(`Token stored successfully for key: ${e}`)}catch(r){throw forget(e),Logger.error(`Error storing token for key: ${e}`,r),r}};const parseTokenData=e=>{if(!e)return null;const{password:r}=e;try{const e=JSON.parse(r);return e&&"object"==typeof e&&"token"in e&&"expiry"in e&&"string"==typeof e.token&&"string"==typeof e.expiry?e:null}catch{return null}};export const getToken=async e=>{if(isSessionKey(e)&&legacyKeys&&await migrateLegacySession(),memo.has(e))return memo.get(e)??null;const r=generation;try{const o=await requireBackend("read a token").getGenericPassword({service:e});let t=null;if(o){const r=parseTokenData(o);if(r)t={token:r.token,expiry:r.expiry};else if(Logger.warn(`Stored credentials for key "${e}" are not a valid token; ignoring them.`),isSessionKey(e))return await endSession("corrupt",!0),null}return r===generation&&memo.set(e,t),t}catch(r){const o=r instanceof Error?r.message:String(r);return o.includes("Key permanently invalidated")||o.includes("Secret invalidated")?(Logger.error(`Stored token for key "${e}" can no longer be decrypted; clearing it.`),isSessionKey(e)?await endSession("corrupt",!0):await removeToken(e),null):(Logger.error(`Error retrieving token for key: ${e}`,r),null)}};export const removeToken=async e=>{forget(e);try{await requireBackend("remove a token").resetGenericPassword({service:e}),Logger.info(`Token removed successfully for key: ${e}`)}catch(r){if(r instanceof Error&&r.message.includes("Item not found"))return void Logger.info(`No token found to remove for key: ${e}`);Logger.error(`Failed to remove token for key: ${e}`,r)}finally{forget(e)}};const isSessionKey=e=>"accessToken"===e||"refreshToken"===e;export const storeSessionUser=async e=>{if(!await Storage.setItem("sessionUser",JSON.stringify(e)))throw new Error("[authStore] could not store the session user.")};export const getSessionUser=async()=>{const e=await Storage.getItem("sessionUser");if(null===e)return null;try{return JSON.parse(e)}catch{return Logger.warn("The stored session user is not valid JSON; clearing it."),await removeSessionUser(),null}};export const removeSessionUser=async()=>{await Storage.removeItem("sessionUser")};let legacyKeys=null,legacyCheck=null;export const setLegacyTokenKeys=e=>{legacyKeys=e,legacyCheck=null};const readLegacyToken=e=>{try{const r=JSON.parse(e);if("string"==typeof r)return""===r.trim()?null:{token:r,expiry:null};if(r&&"object"==typeof r&&"string"==typeof r.token&&"string"==typeof r.expiry)return r}catch{}return""===e.trim()?null:{token:e,expiry:null}},expiryOf=e=>3===e.split(".").length?getJWTExpiry(e)?.toISOString()??null:null,readLegacyRaw=async e=>{const r=await resolveBackend().getGenericPassword({service:e});return r?r.password:null},migrateLegacySession=()=>{if(!legacyKeys)return Promise.resolve();if(legacyCheck)return legacyCheck;const e=legacyKeys;return legacyCheck=(async()=>{try{const r=resolveBackend()
|
|
1
|
+
"use strict";import*as SecureStore from"expo-secure-store";import{Logger}from"../logger/index.js";import{Storage}from"../storage/index.js";import{getJWTExpiry}from"./jwt.js";export const ACCESS_TOKEN_KEY="accessToken";export const REFRESH_TOKEN_KEY="refreshToken";export const SESSION_USER_KEY="sessionUser";export const LEGACY_REFRESH_TOKEN_LIFETIME_MS=2592e6;let backend=null;const keyFor=e=>(e??"default").replace(/[^A-Za-z0-9._-]/g,"_"),expoSecureStoreBackend={setGenericPassword:async(e,r,o)=>(await SecureStore.setItemAsync(keyFor(o?.service),JSON.stringify({username:e,password:r})),!0),getGenericPassword:async e=>{const r=e?.service,o=await SecureStore.getItemAsync(keyFor(r));if(null===o)return!1;const t=JSON.parse(o);return{username:t.username,password:t.password,service:r??"default"}},resetGenericPassword:async e=>(await SecureStore.deleteItemAsync(keyFor(e?.service)),!0)},resolveBackend=()=>backend??expoSecureStoreBackend,memo=new Map;let generation=0;const forget=e=>{generation+=1,void 0===e?memo.clear():memo.delete(e)},requireBackend=e=>{const r=resolveBackend();if(!r){const r=new Error(`[authStore] no secure-store backend available; cannot ${e}.`);throw Logger.error(r.message),r}return r};export const setKeychainImplementation=e=>{backend=e,forget()};export const storeToken=async(e,r,o)=>{Logger.info(`Storing token for key: ${e}`),forget(e);try{const t=JSON.stringify({token:r,expiry:o});await requireBackend("store a token").setGenericPassword("token",t,{service:e}),forget(e),memo.set(e,{token:r,expiry:o}),Logger.info(`Token stored successfully for key: ${e}`)}catch(r){throw forget(e),Logger.error(`Error storing token for key: ${e}`,r),r}};const parseTokenData=e=>{if(!e)return null;const{password:r}=e;try{const e=JSON.parse(r);return e&&"object"==typeof e&&"token"in e&&"expiry"in e&&"string"==typeof e.token&&"string"==typeof e.expiry?e:null}catch{return null}};export const getToken=async e=>{if(isSessionKey(e)&&legacyKeys&&await migrateLegacySession(),memo.has(e))return memo.get(e)??null;const r=generation;try{const o=await requireBackend("read a token").getGenericPassword({service:e});let t=null;if(o){const r=parseTokenData(o);if(r)t={token:r.token,expiry:r.expiry};else if(Logger.warn(`Stored credentials for key "${e}" are not a valid token; ignoring them.`),isSessionKey(e))return await endSession("corrupt",!0),null}return r===generation&&memo.set(e,t),t}catch(r){const o=r instanceof Error?r.message:String(r);return o.includes("Key permanently invalidated")||o.includes("Secret invalidated")?(Logger.error(`Stored token for key "${e}" can no longer be decrypted; clearing it.`),isSessionKey(e)?await endSession("corrupt",!0):await removeToken(e),null):(Logger.error(`Error retrieving token for key: ${e}`,r),null)}};export const removeToken=async e=>{forget(e);try{await requireBackend("remove a token").resetGenericPassword({service:e}),Logger.info(`Token removed successfully for key: ${e}`)}catch(r){if(r instanceof Error&&r.message.includes("Item not found"))return void Logger.info(`No token found to remove for key: ${e}`);Logger.error(`Failed to remove token for key: ${e}`,r)}finally{forget(e)}};const isSessionKey=e=>"accessToken"===e||"refreshToken"===e;export const storeSessionUser=async e=>{if(!await Storage.setItem("sessionUser",JSON.stringify(e)))throw new Error("[authStore] could not store the session user.")};export const getSessionUser=async()=>{const e=await Storage.getItem("sessionUser");if(null===e)return null;try{return JSON.parse(e)}catch{return Logger.warn("The stored session user is not valid JSON; clearing it."),await removeSessionUser(),null}};export const removeSessionUser=async()=>{await Storage.removeItem("sessionUser")};let legacyKeys=null,legacyCheck=null;export const setLegacyTokenKeys=e=>{legacyKeys=e,legacyCheck=null};const readLegacyToken=e=>{try{const r=JSON.parse(e);if("string"==typeof r)return""===r.trim()?null:{token:r,expiry:null};if(r&&"object"==typeof r&&"string"==typeof r.token&&"string"==typeof r.expiry)return r}catch{}return""===e.trim()?null:{token:e,expiry:null}},expiryOf=e=>3===e.split(".").length?getJWTExpiry(e)?.toISOString()??null:null,readLegacyRaw=async e=>{const r=await resolveBackend().getGenericPassword({service:e});return r?r.password:null},migrateLegacySession=()=>{if(!legacyKeys)return Promise.resolve();if(legacyCheck)return legacyCheck;const e=legacyKeys;return legacyCheck=(async()=>{try{const r=resolveBackend();let o=!0;const t=!await r.getGenericPassword({service:"accessToken"})&&!await r.getGenericPassword({service:"refreshToken"}),n=await readLegacyRaw(e.accessToken),s=await readLegacyRaw(e.refreshToken);if(t&&(null!==n||null!==s)){const t=null===n?null:readLegacyToken(n),a=null===s?null:readLegacyToken(s);if(t){const e=t.expiry??expiryOf(t.token)??(new Date).toISOString();await r.setGenericPassword("token",JSON.stringify({token:t.token,expiry:e}),{service:"accessToken"})}if(a){const e=a.expiry??expiryOf(a.token)??new Date(Date.now()+2592e6).toISOString();await r.setGenericPassword("token",JSON.stringify({token:a.token,expiry:e}),{service:"refreshToken"})}if(e.sessionUser){const r=await Storage.getItem(e.sessionUser);null!==r&&(o=await Storage.setItem("sessionUser",r),o||Logger.error("[authStore] could not copy the cached user from the legacy key; leaving it in place"))}null===t&&null===a||(forget(),Logger.breadcrumb("[authStore] moved a session from the legacy token keys"))}for(const o of[e.accessToken,e.refreshToken])await r.resetGenericPassword({service:o}).catch(()=>{});e.sessionUser&&o&&await Storage.removeItem(e.sessionUser)}catch(e){Logger.error("[authStore] could not move the session from the legacy token keys",e)}})(),legacyCheck},listeners=new Set,emitSessionEnded=(e,r)=>{for(const o of[...listeners])try{o(e,r)}catch(e){Logger.error("[authStore] a session-ended listener threw",e)}};export const addSessionEndedListener=e=>(listeners.add(e),()=>{listeners.delete(e)});const endSession=async(e,r,o=null,t=null)=>{const n=r||null!==await getToken("accessToken")||null!==await getToken("refreshToken");await removeToken("accessToken"),await removeToken("refreshToken"),await removeSessionUser(),n&&emitSessionEnded(e,{code:o,detail:t})};export const clearSession=async(e="signedOut",r={})=>endSession(e,!1,r.code??null,r.detail??null);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const asDirectoryPath=e=>e.replace(/\/+$/,"");export const adaptExpoFileSystem=e=>{const t=e?.default??e;if("function"!=typeof t?.File||"function"!=typeof t.File.prototype?.write)return null;const{File:r,Directory:i,Paths:s}=t,o=asDirectoryPath(s.document.uri);return{dirs:{documents:o,cache:asDirectoryPath(s.cache.uri),downloads:o},write:(e,t)=>{const i=new r(e);
|
|
1
|
+
"use strict";const asDirectoryPath=e=>e.replace(/\/+$/,"");export const adaptExpoFileSystem=e=>{const t=e?.default??e;if("function"!=typeof t?.File||"function"!=typeof t.File.prototype?.write)return null;const{File:r,Directory:i,Paths:s}=t,o=asDirectoryPath(s.document.uri);return{dirs:{documents:o,cache:asDirectoryPath(s.cache.uri),downloads:o},write:async(e,t)=>{const i=new r(e);i.create({intermediates:!0,overwrite:!0}),await i.write(t)},exists:e=>Promise.resolve(new r(e).exists),stat:e=>Promise.resolve({size:new r(e).size}),unlink:e=>(new r(e).delete(),Promise.resolve()),mkdir:e=>(new i(e).create({intermediates:!0,idempotent:!0}),Promise.resolve())}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{Platform}from"react-native";import publicClient from"../api/publicClient.js";import userClient from"../api/userClient.js";import{getConfigValue}from"../config/index.js";import{extractApiError}from"../errors/index.js";import{Logger}from"../logger/index.js";import{setCategories}from"./push.js";export const BROADCAST_OPT_OUT_ACTION="broadcast-opt-out";const WITHDRAW_FROM_PUSH_ROUTE="/consent/withdraw-from-push",OPENS_ROUTE="/opens";let broadcastsConfig=null;const reportedOpens=new Set,requireBroadcastsConfig=()=>{if(!broadcastsConfig)throw new Error("[@webority/mobile-core] call initPushBroadcasts before using push broadcasts.");return broadcastsConfig},clientName=()=>[Platform.OS,getConfigValue("appId"),getConfigValue("appVersion")].filter(Boolean).join(" "),toConsent=t=>({status:t.status,statusDateTimeUtc:t.statusDateTimeUtc??null});export const initPushBroadcasts=t=>{if(!t.basePath.startsWith("/")||t.basePath.endsWith("/"))throw new Error("[@webority/mobile-core] PushBroadcastsConfig.basePath must start with / and not end with /.");broadcastsConfig=t,setCategories([{id:t.categoryId,actions:[{id:"broadcast-opt-out",title:t.optOutTitle,opensApp:!1}]}]).catch(t=>Logger.error("[push] registering the broadcast category failed",t))};export const getBroadcastConsent=async()=>{const{basePath:t}=requireBroadcastsConfig();try{const
|
|
1
|
+
"use strict";import{Platform}from"react-native";import publicClient from"../api/publicClient.js";import userClient from"../api/userClient.js";import{getConfigValue}from"../config/index.js";import{extractApiError}from"../errors/index.js";import{Logger}from"../logger/index.js";import{Storage}from"../storage/index.js";import{setCategories}from"./push.js";export const BROADCAST_OPT_OUT_ACTION="broadcast-opt-out";const WITHDRAW_FROM_PUSH_ROUTE="/consent/withdraw-from-push",OPENS_ROUTE="/opens",PENDING_OPT_OUTS_KEY="@webority/push/pending-opt-outs";let broadcastsConfig=null;const reportedOpens=new Set,requireBroadcastsConfig=()=>{if(!broadcastsConfig)throw new Error("[@webority/mobile-core] call initPushBroadcasts before using push broadcasts.");return broadcastsConfig},readPendingOptOuts=async()=>{const t=await Storage.getJson(PENDING_OPT_OUTS_KEY);return Array.isArray(t)?t.filter(t=>"string"==typeof t):[]},savePendingOptOuts=t=>t.length>0?Storage.setJson(PENDING_OPT_OUTS_KEY,t):Storage.removeItem(PENDING_OPT_OUTS_KEY),isRefusal=t=>t>=400&&t<500&&408!==t&&429!==t,sendOptOuts=async(t,e)=>{const o=await readPendingOptOuts();void 0===e||o.includes(e)||(o.push(e),await savePendingOptOuts(o));for(const e of[...o]){try{await publicClient.post(`${t.basePath}${WITHDRAW_FROM_PUSH_ROUTE}`,{token:e})}catch(t){const{status:e}=extractApiError(t);if(!isRefusal(e)){Logger.error(`[push] ${WITHDRAW_FROM_PUSH_ROUTE} failed with status ${e}; the opt-out stays stored and is sent again at the next launch`);continue}Logger.error(`[push] ${WITHDRAW_FROM_PUSH_ROUTE} was refused with status ${e}; the opt-out is dropped`)}o.splice(o.indexOf(e),1),await savePendingOptOuts(o)}};let outbox=Promise.resolve();const queueOptOuts=(t,e)=>(outbox=outbox.then(()=>sendOptOuts(t,e)),outbox),clientName=()=>[Platform.OS,getConfigValue("appId"),getConfigValue("appVersion")].filter(Boolean).join(" "),toConsent=t=>({status:t.status,statusDateTimeUtc:t.statusDateTimeUtc??null});export const initPushBroadcasts=t=>{if(!t.basePath.startsWith("/")||t.basePath.endsWith("/"))throw new Error("[@webority/mobile-core] PushBroadcastsConfig.basePath must start with / and not end with /.");broadcastsConfig=t,setCategories([{id:t.categoryId,actions:[{id:"broadcast-opt-out",title:t.optOutTitle,opensApp:!1}]}]).catch(t=>Logger.error("[push] registering the broadcast category failed",t)),queueOptOuts(t)};export const getBroadcastConsent=async()=>{const{basePath:t}=requireBroadcastsConfig();try{const e=await userClient.get(`${t}/consent`);return toConsent(e.data)}catch(t){throw extractApiError(t)}};export const grantBroadcastConsent=async()=>{const{basePath:t,consentTextVersion:e}=requireBroadcastsConfig();try{const o=await userClient.post(`${t}/consent/grant`,{consentTextVersion:e,source:"MobileApp",client:clientName()});return toConsent(o.data)}catch(t){throw extractApiError(t)}};export const withdrawBroadcastConsent=async()=>{const{basePath:t}=requireBroadcastsConfig();try{const e=await userClient.post(`${t}/consent/withdraw`,{source:"MobileApp",broadcastRecipientId:null,client:clientName()});return toConsent(e.data)}catch(t){throw extractApiError(t)}};export const handleBroadcastAction=async t=>{if("broadcast-opt-out"!==t.actionId||"Broadcast"!==t.data.kind)return;if(!broadcastsConfig)return void Logger.error("[push] a broadcast opt-out arrived before initPushBroadcasts; call it at module scope in the entry file");const e=t.data.optOutToken;e?await queueOptOuts(broadcastsConfig,e):Logger.error("[push] a broadcast opt-out carried no token")};export const handleBroadcastOpen=t=>{const e=t.broadcastRecipientId;"Broadcast"===t.kind&&e&&(broadcastsConfig?reportedOpens.has(e)||(reportedOpens.add(e),userClient.post(`${broadcastsConfig.basePath}/opens`,{broadcastRecipientId:e}).catch(t=>Logger.warn(`[push] /opens failed with status ${extractApiError(t).status}`))):Logger.error("[push] a broadcast open arrived before initPushBroadcasts; call it at module scope in the entry file"))};
|
package/lib/module/push/push.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{useSyncExternalStore}from"react";import{Platform}from"react-native";import{Logger}from"../logger/index.js";let resolved,override=null;export const setPushImplementation=e=>{override=e};export const resolveModules=()=>{if(override)return override;if(void 0!==resolved)return resolved;try{if(require("expo").isRunningInExpoGo())return resolved=null,resolved;const e=require("expo-notifications"),t=require("expo-application");resolved={notifications:e,applicationId:t.applicationId,getApnsEnvironment:()=>t.getIosPushNotificationServiceEnvironmentAsync()}}catch(e){Logger.warn("[push] expo-notifications is not available; push is off",e),resolved=null}return resolved};let state={status:"unknown",enabled:!1};const subscribers=new Set,setState=e=>{state={...state,...e};for(const e of subscribers)e()};let config=null,channelsReady=Promise.resolve(),tokenSubscription=null,actionHandler=null;const receiveHandlers=new Set;let listening=!1,listeningForReceived=!1;const pendingResponses=[],routedAt=new Map,REPEAT_WINDOW_MS=1e4,requireConfig=()=>{if(!config)throw new Error("[@webority/mobile-core] call initPush before enablePush or disablePush.");return config},toPermissionStatus=e=>e.granted?"granted":"denied"===e.status?e.canAskAgain?"denied":"blocked":"undetermined",toStringData=e=>{const t={};for(const[n,o]of Object.entries(e??{}))null!=o&&(t[n]="object"==typeof o?JSON.stringify(o):String(o));return t},contentData=e=>{const t=e.request.content;if(t.data)return toStringData(t.data);if("string"==typeof t.dataString)try{return toStringData(JSON.parse(t.dataString))}catch(e){Logger.error("[push] notification data is not JSON",e)}return{}},triggerData=e=>{const t=e.request.trigger,n={...t?.remoteMessage?.data??{}};for(const[e,o]of Object.entries(t?.payload??{}))"aps"===e||"body"===e&&"object"==typeof o||(n[e]=o);return toStringData(n)},notificationData=e=>({...triggerData(e),...contentData(e)}),responseData=e=>notificationData(e.notification);export const toPushReceived=e=>({notificationId:e.request.identifier,title:e.request.content.title??null,body:e.request.content.body??null,data:notificationData(e)});export const toPushAction=e=>({actionId:e.actionIdentifier,...e.userText?{userText:e.userText}:{},data:responseData(e),notificationId:e.notification.request.identifier});export const toNotificationActions=e=>e.map(e=>({identifier:e.id,buttonTitle:e.title,...e.textInput?{textInput:{submitButtonTitle:e.textInput.submitTitle,placeholder:e.textInput.placeholder}}:{},options:{opensAppToForeground:e.opensApp??!0,isDestructive:e.destructive??!1,isAuthenticationRequired:e.authenticationRequired??!1}}));const routeResponse=async(e,t)=>{const n=`${t.notification.request.identifier}:${t.actionIdentifier}`,o=routedAt.get(n);if(void 0!==o&&Date.now()-o<1e4)return;if(t.actionIdentifier!==e.DEFAULT_ACTION_IDENTIFIER&&actionHandler){routedAt.set(n,Date.now());try{await actionHandler(toPushAction(t))}catch(e){Logger.error("[push] onAction threw",e)}}else if(config){routedAt.set(n,Date.now());try{config.onOpen(responseData(t))}catch(e){Logger.error("[push] onOpen threw",e)}}else pendingResponses.push(t)},drainPending=async e=>{const t=pendingResponses.splice(0);for(const n of t)await routeResponse(e,n)},listenForResponses=e=>{listening||(listening=!0,e.addNotificationResponseReceivedListener(t=>{routeResponse(e,t)}),e.getLastNotificationResponseAsync().then(async t=>(t&&await routeResponse(e,t),e.clearLastNotificationResponseAsync?.())).catch(e=>Logger.error("[push] reading the launch notification failed",e)))};export const routeTaskPayload=async e=>{const t=resolveModules(),n=e;t&&"string"==typeof n?.actionIdentifier&&"string"==typeof n.notification?.request?.identifier&&await routeResponse(t.notifications,n)};const createChannels=async(e,t)=>{for(const n of t)try{await e.setNotificationChannelAsync(n.id,{name:n.name,importance:"high"===n.importance?e.AndroidImportance.HIGH:e.AndroidImportance.DEFAULT})}catch(e){Logger.error(`[push] creating channel ${n.id} failed`,e)}},APNS_ENVIRONMENTS={development:"Development",production:"Production"},readApnsEnvironment=async e=>{try{return APNS_ENVIRONMENTS[await e.getApnsEnvironment()??""]??null}catch(e){return Logger.warn("[push] reading the APNs environment failed",e),null}},deviceTimeZone=()=>Intl.DateTimeFormat().resolvedOptions().timeZone||null,toDevice=async(e,t)=>{const n="android"===e.type?"Fcm":"ios"===e.type?"Apns":null;if(!n||"string"!=typeof e.data)return null;if(!t.applicationId)throw new Error("[@webority/mobile-core] push needs the app bundle id from expo-application.");return{installationId:await requireConfig().getInstallationId(),platform:n,token:e.data,appId:t.applicationId,apnsEnvironment:"Apns"===n?await readApnsEnvironment(t):null,timeZone:deviceTimeZone()}};export const initPush=e=>{const t=null===config;if(config=e,!t)return;const n=resolveModules();if(!n)return void setState({status:"unavailable"});const o=n.notifications;o.setNotificationHandler({handleNotification:async()=>{const e=config?.showInForeground?.()??!0;return{shouldShowBanner:e,shouldShowList:e,shouldPlaySound:e&&(config?.playSoundInForeground?.()??!0),shouldSetBadge:!0}}}),"android"===Platform.OS&&e.androidChannels?.length&&(channelsReady=createChannels(o,e.androidChannels)),listenForResponses(o),drainPending(o),o.getPermissionsAsync().then(e=>setState({status:toPermissionStatus(e)})).catch(e=>Logger.error("[push] permission check failed",e))};let registering=null,registeredKey=null,unregistering=null,tokenDrop=Promise.resolve();const registerOnce=e=>{const t=JSON.stringify(e);if(registering?.key===t)return registering.promise;const n=requireConfig().register(e).then(()=>{registeredKey=t}).finally(()=>{registering?.promise===n&&(registering=null)});return registering={key:t,promise:n},n};export const enablePush=async({prompt:e=!0}={})=>{requireConfig();const t=resolveModules();if(!t)return setState({status:"unavailable"}),"unavailable";const n=t.notifications;await channelsReady,await tokenDrop;let o=await n.getPermissionsAsync();if(!o.granted&&e&&(o=await n.requestPermissionsAsync()),!o.granted){const e=toPermissionStatus(o);return setState({status:e}),e}const i=await toDevice(await n.getDevicePushTokenAsync(),t);return i?(await registerOnce(i),tokenSubscription?.remove(),tokenSubscription=n.addPushTokenListener(e=>{(unregistering??Promise.resolve()).then(()=>state.enabled?toDevice(e,t):null).then(e=>e&&JSON.stringify(e)!==registeredKey?registerOnce(e):void 0).catch(e=>Logger.error("[push] re-registering a new token failed",e))}),setState({status:"granted",enabled:!0}),"granted"):(setState({status:"unavailable"}),"unavailable")};export const readDevicePushToken=async()=>{const e=resolveModules();if(!e)return null;await tokenDrop;if(!(await e.notifications.getPermissionsAsync()).granted)return null;const t=await e.notifications.getDevicePushTokenAsync(),n="android"===t.type?"android":"ios"===t.type?"ios":null;return n&&"string"==typeof t.data?{platform:n,token:t.data}:null};const stopFollowingToken=()=>{tokenSubscription?.remove(),tokenSubscription=null,registeredKey=null,setState({enabled:!1})};export const disablePush=async()=>{const e=requireConfig(),t=await e.getInstallationId();await(registering?.promise.catch(()=>{}));let settle=()=>{};const n=new Promise(e=>{settle=e});unregistering=n;try{await e.unregister(t),stopFollowingToken()}finally{unregistering===n&&(unregistering=null),settle()}};export const resetPush=async()=>{stopFollowingToken();const e=resolveModules();if(!e)return;const t=e.notifications.unregisterForNotificationsAsync();tokenDrop=t.catch(()=>{}),await t};export const setBadgeCount=async e=>{const t=resolveModules();t&&await t.notifications.setBadgeCountAsync(e)};export const dismissAllNotifications=async()=>{const e=resolveModules();if(e)try{await e.notifications.dismissAllNotificationsAsync()}catch(e){Logger.warn("[push] dismissing the notifications failed",e)}};export const setCategories=async e=>{const t=resolveModules();if(t)for(const n of e)await t.notifications.setNotificationCategoryAsync(n.id,toNotificationActions(n.actions))};export const onAction=e=>{actionHandler=e;const t=resolveModules();return t&&(listenForResponses(t.notifications),drainPending(t.notifications)),()=>{actionHandler===e&&(actionHandler=null)}};export const onReceive=e=>{receiveHandlers.add(e);const t=resolveModules();return t&&!listeningForReceived&&(listeningForReceived=!0,t.notifications.addNotificationReceivedListener(e=>{const t=toPushReceived(e);for(const e of[...receiveHandlers])try{e(t)}catch(e){Logger.error("[push] onReceive threw",e)}})),()=>{receiveHandlers.delete(e)}};export const notifyLocal=async({title:e,body:t,data:n})=>{const o=resolveModules();o&&await o.notifications.scheduleNotificationAsync({content:{title:e,body:t,data:n??{}},trigger:null})};const subscribe=e=>(subscribers.add(e),()=>{subscribers.delete(e)}),getSnapshot=()=>state,enable=async()=>{await enablePush()};export const usePush=()=>({...useSyncExternalStore(subscribe,getSnapshot,getSnapshot),enable:enable,disable:disablePush});
|
|
1
|
+
"use strict";import{useSyncExternalStore}from"react";import{Platform}from"react-native";import{Logger}from"../logger/index.js";let resolved,override=null;export const setPushImplementation=e=>{override=e};export const resolveModules=()=>{if(override)return override;if(void 0!==resolved)return resolved;try{if(require("expo").isRunningInExpoGo())return resolved=null,resolved;const e=require("expo-notifications"),t=require("expo-application");resolved={notifications:e,applicationId:t.applicationId,getApnsEnvironment:()=>t.getIosPushNotificationServiceEnvironmentAsync()}}catch(e){Logger.warn("[push] expo-notifications is not available; push is off",e),resolved=null}return resolved};let state={status:"unknown",enabled:!1,registrationError:null};const subscribers=new Set,setState=e=>{state={...state,...e};for(const e of subscribers)e()};let config=null,channelsReady=Promise.resolve(),tokenSubscription=null,actionHandler=null;const receiveHandlers=new Set;let listening=!1,listeningForReceived=!1;const pendingResponses=[],routedAt=new Map,REPEAT_WINDOW_MS=1e4,requireConfig=()=>{if(!config)throw new Error("[@webority/mobile-core] call initPush before enablePush or disablePush.");return config},toPermissionStatus=e=>e.granted?"granted":"denied"===e.status?e.canAskAgain?"denied":"blocked":"undetermined",toStringData=e=>{const t={};for(const[n,o]of Object.entries(e??{}))null!=o&&(t[n]="object"==typeof o?JSON.stringify(o):String(o));return t},contentData=e=>{const t=e.request.content;if(t.data)return toStringData(t.data);if("string"==typeof t.dataString)try{return toStringData(JSON.parse(t.dataString))}catch(e){Logger.error("[push] notification data is not JSON",e)}return{}},triggerData=e=>{const t=e.request.trigger,n={...t?.remoteMessage?.data??{}};for(const[e,o]of Object.entries(t?.payload??{}))"aps"===e||"body"===e&&"object"==typeof o||(n[e]=o);return toStringData(n)},notificationData=e=>({...triggerData(e),...contentData(e)}),responseData=e=>notificationData(e.notification);export const toPushReceived=e=>({notificationId:e.request.identifier,title:e.request.content.title??null,body:e.request.content.body??null,data:notificationData(e)});export const toPushAction=e=>({actionId:e.actionIdentifier,...e.userText?{userText:e.userText}:{},data:responseData(e),notificationId:e.notification.request.identifier});export const toNotificationActions=e=>e.map(e=>({identifier:e.id,buttonTitle:e.title,...e.textInput?{textInput:{submitButtonTitle:e.textInput.submitTitle,placeholder:e.textInput.placeholder}}:{},options:{opensAppToForeground:e.opensApp??!0,isDestructive:e.destructive??!1,isAuthenticationRequired:e.authenticationRequired??!1}}));const routeResponse=async(e,t)=>{const n=`${t.notification.request.identifier}:${t.actionIdentifier}`,o=routedAt.get(n);if(void 0!==o&&Date.now()-o<1e4)return;if(t.actionIdentifier!==e.DEFAULT_ACTION_IDENTIFIER&&actionHandler){routedAt.set(n,Date.now());try{await actionHandler(toPushAction(t))}catch(e){Logger.error("[push] onAction threw",e)}}else if(config){routedAt.set(n,Date.now());try{config.onOpen(responseData(t))}catch(e){Logger.error("[push] onOpen threw",e)}}else pendingResponses.push(t)},drainPending=async e=>{const t=pendingResponses.splice(0);for(const n of t)await routeResponse(e,n)},listenForResponses=e=>{listening||(listening=!0,e.addNotificationResponseReceivedListener(t=>{routeResponse(e,t)}),e.getLastNotificationResponseAsync().then(async t=>(t&&await routeResponse(e,t),e.clearLastNotificationResponseAsync?.())).catch(e=>Logger.error("[push] reading the launch notification failed",e)))};export const routeTaskPayload=async e=>{const t=resolveModules(),n=e;t&&"string"==typeof n?.actionIdentifier&&"string"==typeof n.notification?.request?.identifier&&await routeResponse(t.notifications,n)};const createChannels=async(e,t)=>{for(const n of t)try{await e.setNotificationChannelAsync(n.id,{name:n.name,importance:"high"===n.importance?e.AndroidImportance.HIGH:e.AndroidImportance.DEFAULT})}catch(e){Logger.error(`[push] creating channel ${n.id} failed`,e)}},APNS_ENVIRONMENTS={development:"Development",production:"Production"},readApnsEnvironment=async e=>{try{return APNS_ENVIRONMENTS[await e.getApnsEnvironment()??""]??null}catch(e){return Logger.warn("[push] reading the APNs environment failed",e),null}},deviceTimeZone=()=>Intl.DateTimeFormat().resolvedOptions().timeZone||null,toDevice=async(e,t)=>{const n="android"===e.type?"Fcm":"ios"===e.type?"Apns":null;if(!n||"string"!=typeof e.data)return null;if(!t.applicationId)throw new Error("[@webority/mobile-core] push needs the app bundle id from expo-application.");return{installationId:await requireConfig().getInstallationId(),platform:n,token:e.data,appId:t.applicationId,apnsEnvironment:"Apns"===n?await readApnsEnvironment(t):null,timeZone:deviceTimeZone()}};export const initPush=e=>{const t=null===config;if(config=e,!t)return;const n=resolveModules();if(!n)return void setState({status:"unavailable"});const o=n.notifications;o.setNotificationHandler({handleNotification:async()=>{const e=config?.showInForeground?.()??!0;return{shouldShowBanner:e,shouldShowList:e,shouldPlaySound:e&&(config?.playSoundInForeground?.()??!0),shouldSetBadge:!0}}}),"android"===Platform.OS&&e.androidChannels?.length&&(channelsReady=createChannels(o,e.androidChannels)),listenForResponses(o),drainPending(o),o.getPermissionsAsync().then(e=>setState({status:toPermissionStatus(e)})).catch(e=>Logger.error("[push] permission check failed",e))};let registering=null,registeredKey=null,unregistering=null,tokenDrop=Promise.resolve();const registerOnce=e=>{const t=JSON.stringify(e);if(registering?.key===t)return registering.promise;const n=requireConfig().register(e).then(()=>{registeredKey=t,state.registrationError&&setState({registrationError:null})}).finally(()=>{registering?.promise===n&&(registering=null)});return registering={key:t,promise:n},n};export const enablePush=async({prompt:e=!0}={})=>{requireConfig();const t=resolveModules();if(!t)return setState({status:"unavailable"}),"unavailable";const n=t.notifications;await channelsReady,await tokenDrop;let o=await n.getPermissionsAsync();if(!o.granted&&e&&(o=await n.requestPermissionsAsync()),!o.granted){const e=toPermissionStatus(o);return setState({status:e}),e}const i=await toDevice(await n.getDevicePushTokenAsync(),t);return i?(await registerOnce(i),tokenSubscription?.remove(),tokenSubscription=n.addPushTokenListener(e=>{(unregistering??Promise.resolve()).then(()=>state.enabled?toDevice(e,t):null).then(e=>e&&JSON.stringify(e)!==registeredKey?registerOnce(e):void 0).catch(e=>{Logger.error("[push] re-registering a new token failed",e),setState({registrationError:e instanceof Error?e:new Error(String(e))})})}),setState({status:"granted",enabled:!0}),"granted"):(setState({status:"unavailable"}),"unavailable")};export const readDevicePushToken=async()=>{const e=resolveModules();if(!e)return null;await tokenDrop;if(!(await e.notifications.getPermissionsAsync()).granted)return null;const t=await e.notifications.getDevicePushTokenAsync(),n="android"===t.type?"android":"ios"===t.type?"ios":null;return n&&"string"==typeof t.data?{platform:n,token:t.data}:null};const stopFollowingToken=()=>{tokenSubscription?.remove(),tokenSubscription=null,registeredKey=null,setState({enabled:!1,registrationError:null})};export const disablePush=async()=>{const e=requireConfig(),t=await e.getInstallationId();await(registering?.promise.catch(()=>{}));let settle=()=>{};const n=new Promise(e=>{settle=e});unregistering=n;try{await e.unregister(t),stopFollowingToken()}finally{unregistering===n&&(unregistering=null),settle()}};export const resetPush=async()=>{stopFollowingToken();const e=resolveModules();if(!e)return;const t=e.notifications.unregisterForNotificationsAsync();tokenDrop=t.catch(()=>{}),await t};export const setBadgeCount=async e=>{const t=resolveModules();t&&await t.notifications.setBadgeCountAsync(e)};export const dismissAllNotifications=async()=>{const e=resolveModules();if(e)try{await e.notifications.dismissAllNotificationsAsync()}catch(e){Logger.warn("[push] dismissing the notifications failed",e)}};export const setCategories=async e=>{const t=resolveModules();if(t)for(const n of e)await t.notifications.setNotificationCategoryAsync(n.id,toNotificationActions(n.actions))};export const onAction=e=>{actionHandler=e;const t=resolveModules();return t&&(listenForResponses(t.notifications),drainPending(t.notifications)),()=>{actionHandler===e&&(actionHandler=null)}};export const onReceive=e=>{receiveHandlers.add(e);const t=resolveModules();return t&&!listeningForReceived&&(listeningForReceived=!0,t.notifications.addNotificationReceivedListener(e=>{const t=toPushReceived(e);for(const e of[...receiveHandlers])try{e(t)}catch(e){Logger.error("[push] onReceive threw",e)}})),()=>{receiveHandlers.delete(e)}};export const notifyLocal=async({title:e,body:t,data:n})=>{const o=resolveModules();o&&await o.notifications.scheduleNotificationAsync({content:{title:e,body:t,data:n??{}},trigger:null})};const subscribe=e=>(subscribers.add(e),()=>{subscribers.delete(e)}),getSnapshot=()=>state,enable=async()=>{await enablePush()};export const usePush=()=>({...useSyncExternalStore(subscribe,getSnapshot,getSnapshot),enable:enable,disable:disablePush});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{useEffect,useRef}from"react";import{Platform}from"react-native";import{Logger}from"../logger/index.js";const screenCapture=()=>require("expo-screen-capture"),report=e=>r=>{Logger.error(`[@webority/mobile-core] useSecureScreen could not ${e}.`,r)};let nextKey=0,appSwitcherHolders=0;export const useSecureScreen=(e={})=>{const{focused:r=!0}=e,t=useRef(null);null===t.current&&(nextKey+=1,t.current=`webority-secure-screen-${nextKey}`),useEffect(()=>{if(!r)return;const e=t.current,c=screenCapture();c.preventScreenCaptureAsync(e).catch(
|
|
1
|
+
"use strict";import{useEffect,useRef,useState}from"react";import{Platform}from"react-native";import{Logger}from"../logger/index.js";const screenCapture=()=>require("expo-screen-capture"),report=e=>r=>{Logger.error(`[@webority/mobile-core] useSecureScreen could not ${e}.`,r)},protectionFailed=(e,r)=>t=>{report(e)(t),r(new Error(`[@webority/mobile-core] useSecureScreen could not ${e}, so the screen is not protected.`,{cause:t}))};let nextKey=0,appSwitcherHolders=0;export const useSecureScreen=(e={})=>{const{focused:r=!0}=e,t=useRef(null);null===t.current&&(nextKey+=1,t.current=`webority-secure-screen-${nextKey}`);const[c,o]=useState(null);if(useEffect(()=>{if(!r)return;const e=t.current,c=screenCapture();c.preventScreenCaptureAsync(e).catch(protectionFailed("block screen capture",o));const s="ios"===Platform.OS;return s&&(appSwitcherHolders+=1,1===appSwitcherHolders&&c.enableAppSwitcherProtectionAsync().catch(protectionFailed("hide the app switcher snapshot",o))),()=>{c.allowScreenCaptureAsync(e).catch(report("release screen capture")),s&&(appSwitcherHolders-=1,0===appSwitcherHolders&&c.disableAppSwitcherProtectionAsync().catch(report("restore the app switcher snapshot")))}},[r]),c)throw c};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{DeviceEventEmitter,Platform}from"react-native";import{Logger}from"../logger/index.js";const OTP_EVENT="WeborityMobileCoreSmsRetrieved",ERROR_EVENT="WeborityMobileCoreSmsRetrieverError";let nativeModule,backend=null;export const setSmsRetrieverImplementation=e=>{backend=e};const resolveNativeModule=()=>{if(void 0!==nativeModule)return nativeModule;if("android"!==Platform.OS)return nativeModule=null,null;try{nativeModule=require("../specs/NativeSmsRetriever").default??null}catch(e){Logger.warn("[smsRetriever] native module not available",e),nativeModule=null}return nativeModule??null},defaultBackend={getAppHash:async()=>{const e=resolveNativeModule();if(!e)throw new Error("[smsRetriever] getAppHash: native module unavailable (Android only).");return e.getAppHash()},startListening:(e,t)=>{const r=resolveNativeModule();if(!r)return t?.({type:"SERVICE_UNAVAILABLE",message:"SMS Retriever is Android-only, or the native module is not linked."}),{remove:()=>{}};const
|
|
1
|
+
"use strict";import{DeviceEventEmitter,Platform}from"react-native";import{Logger}from"../logger/index.js";const OTP_EVENT="WeborityMobileCoreSmsRetrieved",ERROR_EVENT="WeborityMobileCoreSmsRetrieverError";let nativeModule,backend=null;export const setSmsRetrieverImplementation=e=>{backend=e};const resolveNativeModule=()=>{if(void 0!==nativeModule)return nativeModule;if("android"!==Platform.OS)return nativeModule=null,null;try{nativeModule=require("../specs/NativeSmsRetriever").default??null}catch(e){Logger.warn("[smsRetriever] native module not available",e),nativeModule=null}return nativeModule??null},defaultBackend={getAppHash:async()=>{const e=resolveNativeModule();if(!e)throw new Error("[smsRetriever] getAppHash: native module unavailable (Android only).");return e.getAppHash()},startListening:(e,t)=>{const r=resolveNativeModule();if(!r)return t?.({type:"SERVICE_UNAVAILABLE",message:"SMS Retriever is Android-only, or the native module is not linked."}),{remove:()=>{}};const n=DeviceEventEmitter.addListener(OTP_EVENT,t=>e(t.message)),i=t?DeviceEventEmitter.addListener(ERROR_EVENT,e=>t(e)):null;try{r.startSMSListener()}catch(e){if(n.remove(),i?.remove(),!t)throw e;return t({type:"UNKNOWN_ERROR",message:e instanceof Error?e.message:String(e)}),{remove:()=>{}}}return{remove:()=>{n.remove(),i?.remove();try{r.stopSMSListener()}catch(e){Logger.error("[smsRetriever] stopSMSListener failed",e)}}}}};export const SmsRetriever={isAvailable:()=>null!==resolveNativeModule(),getAppHash:()=>(backend??defaultBackend).getAppHash(),startListening:(e,t)=>(backend??defaultBackend).startListening(e,t)};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{useSyncExternalStore}from"react";import{AppState,Platform}from"react-native";import{getConfigValue}from"../config/index.js";import{ENVIRONMENT_APP_ID_SUFFIX}from"../config/appIdentity.js";import{Logger}from"../logger/index.js";import{Storage}from"../storage/index.js";const PREFIX="[@webority/mobile-core] OTA updates:",REPORTED_KEY="@webority/ota/last-reported-update-id";export const OTA_LAST_LAUNCH_KEY="@webority/ota/last-launch";const ENV_IDENTITY_SUFFIXES=Object.values(ENVIRONMENT_APP_ID_SUFFIX).filter(e=>""!==e);export const DEFAULT_MIN_CHECK_INTERVAL_MS=9e5;const EVENT_TIMEOUT_MS=1e4;let resolved,override=null;export const setOtaUpdatesImplementation=e=>{override=e};const resolveUpdates=()=>{if(override)return override;if(void 0!==resolved)return resolved;try{resolved=require("expo-updates")}catch{resolved=null}return resolved},INITIAL_STATE={status:"unavailable",runningUpdateId:null,error:null,lastCheckedAt:null};let state=INITIAL_STATE;const subscribers=new Set,setState=e=>{state={...state,...e};for(const e of subscribers)e()};let config=null,stateSubscription=null,appStateSubscription=null,checking=null,lastCheckStartedAt=0,lastReportedError=null;const messageOf=e=>e instanceof Error?e.message:String(e);export const normalizeAppIdentity=e=>{const t=String(e??"").trim().toLowerCase(),r=ENV_IDENTITY_SUFFIXES.find(e=>t.endsWith(e));return r?t.slice(0,-r.length):t};const ownIdentity=()=>config?.appIdentifier??getConfigValue("appId",null)??null,identityMismatch=e=>{const t=e?.extra?.webority?.appIdentifier;if(!t)return null;const r=ownIdentity();return r&&normalizeAppIdentity(t)===normalizeAppIdentity(r)?null:`identity mismatch: the update is for '${t}' but this app is '${r??"unset"}'`},postEvent=async(e,t,r)=>{const a=config?.serverUrl;if(!a||!e)return;const n=new AbortController,s=setTimeout(()=>n.abort(),1e4);try{await fetch(`${a.replace(/\/+$/,"")}/ota/updates/${encodeURIComponent(e)}/events`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:t,platform:Platform.OS,runtimeVersion:resolveUpdates()?.runtimeVersion??null,message:r}),signal:n.signal})}catch(e){Logger.info(`${PREFIX} the ${t} event was not reported: ${messageOf(e)}`)}finally{clearTimeout(s)}},reportError=(e,t)=>{setState({status:"error",error:t});const r=`${e??""}|${t}`;r!==lastReportedError&&(lastReportedError=r,Logger.error(`${PREFIX} ${t}`),postEvent(e,"error",t))},recordLaunch=async e=>{const t={updateId:e.updateId,channel:e.channel??null,runtimeVersion:e.runtimeVersion,isEmbeddedLaunch:e.isEmbeddedLaunch,isEmergencyLaunch:e.isEmergencyLaunch??!1,emergencyLaunchReason:e.emergencyLaunchReason??null,launchedAtUtc:(new Date).toISOString()};await Storage.setItem(OTA_LAST_LAUNCH_KEY,JSON.stringify(t))||Logger.error(`${PREFIX} the launch record was not saved`)},reportRunningUpdate=async e=>{if(await recordLaunch(e),e.isEmbeddedLaunch||!e.updateId)return;const t=identityMismatch(e.manifest);t?reportError(e.updateId,t):await Storage.getItem(REPORTED_KEY)!==e.updateId&&(await postEvent(e.updateId,"success"),await Storage.setItem(REPORTED_KEY,e.updateId),Logger.info(`${PREFIX} running update ${e.updateId}`))},onStateChange=e=>{const t=e.downloadError??e.checkError;if(t){const r=e.latestManifest?.id??resolveUpdates()?.updateId;return void reportError(r,t.message)}e.isChecking?setState({status:"checking"}):e.isDownloading?setState({status:"downloading"}):e.isUpdatePending&&setState({status:"ready",error:null})};export const checkForOtaUpdate=()=>{const e=resolveUpdates();if(!config||!e?.isEnabled)return Promise.resolve("unavailable");if(checking)return checking;lastCheckStartedAt=Date.now();return checking=(async()=>{try{setState({status:"checking"});const t=await e.checkForUpdateAsync();if(t.isAvailable){const e=identityMismatch(t.manifest);if(e)return reportError(t.manifest?.id,e),"error"}return t.isAvailable||t.isRollBackToEmbedded?(setState({status:"downloading"}),await e.fetchUpdateAsync(),setState({status:"ready",error:null}),"ready"):(setState({status:"ready"===state.status?"ready":"idle",error:null}),state.status)}catch(t){return reportError(e.updateId,messageOf(t)),"error"}finally{setState({lastCheckedAt:Date.now()}),checking=null}})(),checking};const onAppStateChange=e=>{if("active"!==e||!1===config?.checkOnForeground)return;const t=config?.minCheckIntervalMs??9e5;Date.now()-lastCheckStartedAt<t||checkForOtaUpdate()};export const initOtaUpdates=e=>{const t=null===config;if(config=e,!t)return;const r=resolveUpdates();if(!r?.isEnabled)return void setState({status:"unavailable"});setState({status:"idle",runningUpdateId:r.isEmbeddedLaunch?null:r.updateId}),reportRunningUpdate(r).catch(e=>{Logger.info(`${PREFIX} start-up report failed: ${messageOf(e)}`)}),"function"==typeof r.addUpdatesStateChangeListener&&(stateSubscription=r.addUpdatesStateChangeListener(e=>onStateChange(e.context))),appStateSubscription=AppState.addEventListener("change",onAppStateChange);"ON_LOAD"===r.checkAutomatically||"WIFI_ONLY"===r.checkAutomatically||checkForOtaUpdate()};export const applyOtaUpdate=async()=>{const e=resolveUpdates();e?.isEnabled&&"ready"===state.status&&await e.reloadAsync()};export const stopOtaUpdates=()=>{stateSubscription?.remove(),appStateSubscription?.remove(),stateSubscription=null,appStateSubscription=null,config=null,checking=null,lastCheckStartedAt=0,lastReportedError=null,resolved=void 0,setState(INITIAL_STATE)};const subscribe=e=>(subscribers.add(e),()=>{subscribers.delete(e)}),getSnapshot=()=>state;export const useOtaUpdates=()=>({...useSyncExternalStore(subscribe,getSnapshot,getSnapshot),check:checkForOtaUpdate,apply:applyOtaUpdate});
|
|
1
|
+
"use strict";import{useSyncExternalStore}from"react";import{AppState,Platform}from"react-native";import{getConfigValue}from"../config/index.js";import{ENVIRONMENT_APP_ID_SUFFIX}from"../config/appIdentity.js";import{Logger}from"../logger/index.js";import{Storage}from"../storage/index.js";const PREFIX="[@webority/mobile-core] OTA updates:",REPORTED_KEY="@webority/ota/last-reported-update-id";export const OTA_LAST_LAUNCH_KEY="@webority/ota/last-launch";const ENV_IDENTITY_SUFFIXES=Object.values(ENVIRONMENT_APP_ID_SUFFIX).filter(e=>""!==e);export const DEFAULT_MIN_CHECK_INTERVAL_MS=9e5;const EVENT_TIMEOUT_MS=1e4;let resolved,override=null;export const setOtaUpdatesImplementation=e=>{override=e};const resolveUpdates=()=>{if(__DEV__)return null;if(override)return override;if(void 0!==resolved)return resolved;try{resolved=require("expo-updates")}catch{resolved=null}return resolved},INITIAL_STATE={status:"unavailable",runningUpdateId:null,error:null,lastCheckedAt:null};let state=INITIAL_STATE;const subscribers=new Set,setState=e=>{state={...state,...e};for(const e of subscribers)e()};let config=null,stateSubscription=null,appStateSubscription=null,checking=null,lastCheckStartedAt=0,lastReportedError=null;const messageOf=e=>e instanceof Error?e.message:String(e);export const normalizeAppIdentity=e=>{const t=String(e??"").trim().toLowerCase(),r=ENV_IDENTITY_SUFFIXES.find(e=>t.endsWith(e));return r?t.slice(0,-r.length):t};const ownIdentity=()=>config?.appIdentifier??getConfigValue("appId",null)??null,identityMismatch=e=>{const t=e?.extra?.webority?.appIdentifier;if(!t)return null;const r=ownIdentity();return r&&normalizeAppIdentity(t)===normalizeAppIdentity(r)?null:`identity mismatch: the update is for '${t}' but this app is '${r??"unset"}'`},postEvent=async(e,t,r)=>{const a=config?.serverUrl;if(!a||!e)return;const n=new AbortController,s=setTimeout(()=>n.abort(),1e4);try{await fetch(`${a.replace(/\/+$/,"")}/ota/updates/${encodeURIComponent(e)}/events`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:t,platform:Platform.OS,runtimeVersion:resolveUpdates()?.runtimeVersion??null,message:r}),signal:n.signal})}catch(e){Logger.info(`${PREFIX} the ${t} event was not reported: ${messageOf(e)}`)}finally{clearTimeout(s)}},reportError=(e,t)=>{setState({status:"error",error:t});const r=`${e??""}|${t}`;r!==lastReportedError&&(lastReportedError=r,Logger.error(`${PREFIX} ${t}`),postEvent(e,"error",t))},recordLaunch=async e=>{const t={updateId:e.updateId,channel:e.channel??null,runtimeVersion:e.runtimeVersion,isEmbeddedLaunch:e.isEmbeddedLaunch,isEmergencyLaunch:e.isEmergencyLaunch??!1,emergencyLaunchReason:e.emergencyLaunchReason??null,launchedAtUtc:(new Date).toISOString()};await Storage.setItem(OTA_LAST_LAUNCH_KEY,JSON.stringify(t))||Logger.error(`${PREFIX} the launch record was not saved`)},reportRunningUpdate=async e=>{if(await recordLaunch(e),e.isEmbeddedLaunch||!e.updateId)return;const t=identityMismatch(e.manifest);t?reportError(e.updateId,t):await Storage.getItem(REPORTED_KEY)!==e.updateId&&(await postEvent(e.updateId,"success"),await Storage.setItem(REPORTED_KEY,e.updateId),Logger.info(`${PREFIX} running update ${e.updateId}`))},onStateChange=e=>{const t=e.downloadError??e.checkError;if(t){const r=e.latestManifest?.id??resolveUpdates()?.updateId;return void reportError(r,t.message)}e.isChecking?setState({status:"checking"}):e.isDownloading?setState({status:"downloading"}):e.isUpdatePending&&setState({status:"ready",error:null})};export const checkForOtaUpdate=()=>{const e=resolveUpdates();if(!config||!e?.isEnabled)return Promise.resolve("unavailable");if(checking)return checking;lastCheckStartedAt=Date.now();return checking=(async()=>{try{setState({status:"checking"});const t=await e.checkForUpdateAsync();if(t.isAvailable){const e=identityMismatch(t.manifest);if(e)return reportError(t.manifest?.id,e),"error"}return t.isAvailable||t.isRollBackToEmbedded?(setState({status:"downloading"}),await e.fetchUpdateAsync(),setState({status:"ready",error:null}),"ready"):(setState({status:"ready"===state.status?"ready":"idle",error:null}),state.status)}catch(t){return reportError(e.updateId,messageOf(t)),"error"}finally{setState({lastCheckedAt:Date.now()}),checking=null}})(),checking};const onAppStateChange=e=>{if("active"!==e||!1===config?.checkOnForeground)return;const t=config?.minCheckIntervalMs??9e5;Date.now()-lastCheckStartedAt<t||checkForOtaUpdate()};export const initOtaUpdates=e=>{const t=null===config;if(config=e,!t)return;const r=resolveUpdates();if(!r?.isEnabled)return void setState({status:"unavailable"});setState({status:"idle",runningUpdateId:r.isEmbeddedLaunch?null:r.updateId}),reportRunningUpdate(r).catch(e=>{Logger.info(`${PREFIX} start-up report failed: ${messageOf(e)}`)}),"function"==typeof r.addUpdatesStateChangeListener&&(stateSubscription=r.addUpdatesStateChangeListener(e=>onStateChange(e.context))),appStateSubscription=AppState.addEventListener("change",onAppStateChange);"ON_LOAD"===r.checkAutomatically||"WIFI_ONLY"===r.checkAutomatically||checkForOtaUpdate()};export const applyOtaUpdate=async()=>{const e=resolveUpdates();e?.isEnabled&&"ready"===state.status&&await e.reloadAsync()};export const stopOtaUpdates=()=>{stateSubscription?.remove(),appStateSubscription?.remove(),stateSubscription=null,appStateSubscription=null,config=null,checking=null,lastCheckStartedAt=0,lastReportedError=null,resolved=void 0,setState(INITIAL_STATE)};const subscribe=e=>(subscribers.add(e),()=>{subscribers.delete(e)}),getSnapshot=()=>state;export const useOtaUpdates=()=>({...useSyncExternalStore(subscribe,getSnapshot,getSnapshot),check:checkForOtaUpdate,apply:applyOtaUpdate});
|
|
@@ -3,6 +3,11 @@ export interface FetchRetryPolicy {
|
|
|
3
3
|
retries?: number;
|
|
4
4
|
/** `attempt` is 1-based: 1 is the first resend. */
|
|
5
5
|
retryDelayMs?: (attempt: number) => number;
|
|
6
|
+
/** Treat this request as a read: it changes nothing on the server, so it is resent like a GET. */
|
|
7
|
+
sideEffectFree?: boolean;
|
|
6
8
|
}
|
|
9
|
+
/**
|
|
10
|
+
* A write is resent only under the shared rule in retry.ts. A rejection that is not a TypeError is thrown at once, not retried.
|
|
11
|
+
*/
|
|
7
12
|
export declare const fetchWithRetry: (send: typeof fetch, url: string, init: RequestInit, policy?: FetchRetryPolicy) => Promise<Response>;
|
|
8
13
|
//# sourceMappingURL=fetchRetry.d.ts.map
|
|
@@ -18,6 +18,7 @@ declare module "axios" {
|
|
|
18
18
|
*/
|
|
19
19
|
export declare const IDEMPOTENCY_KEY_HEADER = "Idempotency-Key";
|
|
20
20
|
export declare const isRetryableStatus: (status: number | undefined) => boolean;
|
|
21
|
+
export declare const isIdempotentMethod: (method: string) => boolean;
|
|
21
22
|
export declare const isNeverSentError: (error: AxiosError) => boolean;
|
|
22
23
|
/**
|
|
23
24
|
* The wait a refusal named, in milliseconds: the `Retry-After` header (seconds).
|
|
@@ -25,6 +26,18 @@ export declare const isNeverSentError: (error: AxiosError) => boolean;
|
|
|
25
26
|
* lists it in `Access-Control-Expose-Headers`.
|
|
26
27
|
*/
|
|
27
28
|
export declare const retryAfterMs: (error: AxiosError) => number | null;
|
|
29
|
+
/** What a failed request tells the shared rule, whichever platform's client sent it. */
|
|
30
|
+
export interface RetryFacts {
|
|
31
|
+
/** The request is a read, or a method a second send cannot repeat a write with (GET, HEAD, OPTIONS, PUT, DELETE). */
|
|
32
|
+
idempotent: boolean;
|
|
33
|
+
/** `undefined` when no answer came back. */
|
|
34
|
+
status: number | undefined;
|
|
35
|
+
/** The wait the refusal named, in milliseconds; `null` when it named none. */
|
|
36
|
+
namedWaitMs: number | null;
|
|
37
|
+
/** The request carries a non-empty `Idempotency-Key` header. */
|
|
38
|
+
hasIdempotencyKey: boolean;
|
|
39
|
+
}
|
|
40
|
+
export declare const isRetryableRequest: (facts: RetryFacts) => boolean;
|
|
28
41
|
/**
|
|
29
42
|
* The one retry rule both platforms share:
|
|
30
43
|
* - a request that provably never reached the server is resent, whatever its method;
|
|
@@ -18,6 +18,10 @@ export declare const SESSION_EXPIRED_CODE = "session_expired";
|
|
|
18
18
|
export interface RefreshableStore {
|
|
19
19
|
dispatch: (action: unknown) => unknown;
|
|
20
20
|
}
|
|
21
|
+
/** A failure that proves the session is over, as opposed to one worth retrying later. */
|
|
22
|
+
export declare class SessionEndedError extends Error {
|
|
23
|
+
constructor(message: string);
|
|
24
|
+
}
|
|
21
25
|
export declare const injectStore: <S>(_store: S) => void;
|
|
22
26
|
export declare const injectUserAuth: (options: UserAuthOptions) => void;
|
|
23
27
|
/**
|
|
@@ -59,10 +63,12 @@ export declare const waitForSessionReplacement: () => Promise<void>;
|
|
|
59
63
|
export declare const currentTokenIfReplaced: (sentToken: string | null) => Promise<string | null>;
|
|
60
64
|
/** Wait for the in-flight refresh without joining it: resolved or rejected by processQueue. */
|
|
61
65
|
export declare const queueBehindRefresh: () => Promise<string>;
|
|
66
|
+
/** True when a failure from the refresh proves the session is over (refreshAccessToken has already logged it once), as opposed to a fault worth an error line. */
|
|
67
|
+
export declare const isSessionEnd: (error: unknown) => boolean;
|
|
62
68
|
/**
|
|
63
69
|
* Stores the session a flagged request's response carries, read the way refresh responses are,
|
|
64
70
|
* before the replacement window closes, so a request waiting on the window retries with the new
|
|
65
|
-
* token. A body without tokens
|
|
71
|
+
* token. A body without tokens rejects, like a failed keychain write, so the request that carried it fails instead of resolving with a session nobody stored.
|
|
66
72
|
*/
|
|
67
73
|
export declare const storeReplacementSession: (data: unknown) => Promise<void>;
|
|
68
74
|
/**
|
|
@@ -30,6 +30,7 @@ export interface FormatCurrencyOptions extends Omit<Intl.NumberFormatOptions, "s
|
|
|
30
30
|
* its group sizes and symbol placement ("₹1.50.000,50" for `'CommaWithPointGroups'`).
|
|
31
31
|
* A numeric string reads as its number. For money the API carries in minor units (paise),
|
|
32
32
|
* use `formatMinor`.
|
|
33
|
+
* The code is not checked against the ISO 4217 list: a well-formed three-letter code the engine does not know prints as the code itself ("XYZ 1,234.00"), and only a malformed code or locale throws a RangeError.
|
|
33
34
|
*
|
|
34
35
|
* @example
|
|
35
36
|
* formatCurrency(150000, { currency: 'INR' }) // ₹1,50,000
|
|
@@ -20,6 +20,7 @@ export declare const BROADCAST_OPT_OUT_ACTION = "broadcast-opt-out";
|
|
|
20
20
|
* Wires the broadcast opt-out for this app. Call it at module scope in the entry
|
|
21
21
|
* file, before definePushActionTask from `/push/task`: a tap on a killed Android
|
|
22
22
|
* app runs that background task without the UI, so the config must already exist.
|
|
23
|
+
* It also sends again any opt-out a failed send left stored.
|
|
23
24
|
*/
|
|
24
25
|
export declare const initPushBroadcasts: (config: PushBroadcastsConfig) => void;
|
|
25
26
|
export declare const getBroadcastConsent: () => Promise<BroadcastConsent>;
|
|
@@ -28,7 +29,8 @@ export declare const withdrawBroadcastConsent: () => Promise<BroadcastConsent>;
|
|
|
28
29
|
/**
|
|
29
30
|
* Handles the opt-out button. Call it from the action handler of definePushActionTask,
|
|
30
31
|
* then run the app's own actions. Never throws: a background task has no screen to
|
|
31
|
-
* show a failure on.
|
|
32
|
+
* show a failure on. A send that fails is kept in storage and sent again at the next
|
|
33
|
+
* launch and the next opt-out. Logs never carry the token.
|
|
32
34
|
*/
|
|
33
35
|
export declare const handleBroadcastAction: PushActionHandler;
|
|
34
36
|
/**
|
|
@@ -95,6 +95,8 @@ export interface PushState {
|
|
|
95
95
|
status: PushStatus;
|
|
96
96
|
/** True once this process has registered the device, false after `disablePush` or `resetPush`. */
|
|
97
97
|
enabled: boolean;
|
|
98
|
+
/** The error from the last failed re-registration of a rotated device token, or null. Cleared when a registration succeeds and by `disablePush` and `resetPush`. `enablePush` registers on every run, so calling it again retries. */
|
|
99
|
+
registrationError: Error | null;
|
|
98
100
|
}
|
|
99
101
|
interface PermissionResponseLike {
|
|
100
102
|
status: "granted" | "denied" | "undetermined";
|
|
@@ -225,6 +227,7 @@ export declare const initPush: (next: PushConfig) => void;
|
|
|
225
227
|
* already granted registers, and any other resolves with its status
|
|
226
228
|
* (`undetermined` when the person has not been asked yet, `denied` when refused
|
|
227
229
|
* and the prompt can still show, `blocked` when only Settings can turn it on).
|
|
230
|
+
* A failed re-registration of a rotated token is logged and shown as `usePush().registrationError`.
|
|
228
231
|
*/
|
|
229
232
|
export declare const enablePush: ({ prompt }?: EnablePushOptions) => Promise<PushStatus>;
|
|
230
233
|
/** Null when push is unavailable in this build or permission is not granted. Never prompts or registers. */
|
|
@@ -9,7 +9,10 @@ export interface SecureScreenOptions {
|
|
|
9
9
|
/**
|
|
10
10
|
* Blocks capture while the calling screen is focused and releases it on blur
|
|
11
11
|
* or unmount. Each call holds its own claim, so two secure screens on the stack
|
|
12
|
-
* never release each other's protection.
|
|
12
|
+
* never release each other's protection. When blocking capture or hiding the app
|
|
13
|
+
* switcher snapshot fails, the failure is logged and the screen throws on its next
|
|
14
|
+
* render, so an error boundary shows instead of an unprotected screen. A failure
|
|
15
|
+
* to release is only logged.
|
|
13
16
|
*
|
|
14
17
|
* ```tsx
|
|
15
18
|
* import { useIsFocused } from '@react-navigation/native';
|
|
@@ -17,6 +17,7 @@ export declare const setSmsRetrieverImplementation: (impl: SmsRetrieverBackend |
|
|
|
17
17
|
* (`getAppHash`) the backend appends to the message. Android only; every
|
|
18
18
|
* method is safe to call on iOS and resolves/reports unavailable rather than
|
|
19
19
|
* throwing, so a caller doesn't need a platform check at every call site.
|
|
20
|
+
* A native listener that fails to start is reported through `onError` as `UNKNOWN_ERROR`; without an `onError` it throws.
|
|
20
21
|
*
|
|
21
22
|
* OTP extraction is left to the caller — `onMessage` receives the raw SMS
|
|
22
23
|
* text, since the expected OTP format (digit count, prefix) is a backend
|
|
@@ -3,6 +3,11 @@ export interface FetchRetryPolicy {
|
|
|
3
3
|
retries?: number;
|
|
4
4
|
/** `attempt` is 1-based: 1 is the first resend. */
|
|
5
5
|
retryDelayMs?: (attempt: number) => number;
|
|
6
|
+
/** Treat this request as a read: it changes nothing on the server, so it is resent like a GET. */
|
|
7
|
+
sideEffectFree?: boolean;
|
|
6
8
|
}
|
|
9
|
+
/**
|
|
10
|
+
* A write is resent only under the shared rule in retry.ts. A rejection that is not a TypeError is thrown at once, not retried.
|
|
11
|
+
*/
|
|
7
12
|
export declare const fetchWithRetry: (send: typeof fetch, url: string, init: RequestInit, policy?: FetchRetryPolicy) => Promise<Response>;
|
|
8
13
|
//# sourceMappingURL=fetchRetry.d.ts.map
|
|
@@ -18,6 +18,7 @@ declare module "axios" {
|
|
|
18
18
|
*/
|
|
19
19
|
export declare const IDEMPOTENCY_KEY_HEADER = "Idempotency-Key";
|
|
20
20
|
export declare const isRetryableStatus: (status: number | undefined) => boolean;
|
|
21
|
+
export declare const isIdempotentMethod: (method: string) => boolean;
|
|
21
22
|
export declare const isNeverSentError: (error: AxiosError) => boolean;
|
|
22
23
|
/**
|
|
23
24
|
* The wait a refusal named, in milliseconds: the `Retry-After` header (seconds).
|
|
@@ -25,6 +26,18 @@ export declare const isNeverSentError: (error: AxiosError) => boolean;
|
|
|
25
26
|
* lists it in `Access-Control-Expose-Headers`.
|
|
26
27
|
*/
|
|
27
28
|
export declare const retryAfterMs: (error: AxiosError) => number | null;
|
|
29
|
+
/** What a failed request tells the shared rule, whichever platform's client sent it. */
|
|
30
|
+
export interface RetryFacts {
|
|
31
|
+
/** The request is a read, or a method a second send cannot repeat a write with (GET, HEAD, OPTIONS, PUT, DELETE). */
|
|
32
|
+
idempotent: boolean;
|
|
33
|
+
/** `undefined` when no answer came back. */
|
|
34
|
+
status: number | undefined;
|
|
35
|
+
/** The wait the refusal named, in milliseconds; `null` when it named none. */
|
|
36
|
+
namedWaitMs: number | null;
|
|
37
|
+
/** The request carries a non-empty `Idempotency-Key` header. */
|
|
38
|
+
hasIdempotencyKey: boolean;
|
|
39
|
+
}
|
|
40
|
+
export declare const isRetryableRequest: (facts: RetryFacts) => boolean;
|
|
28
41
|
/**
|
|
29
42
|
* The one retry rule both platforms share:
|
|
30
43
|
* - a request that provably never reached the server is resent, whatever its method;
|
|
@@ -18,6 +18,10 @@ export declare const SESSION_EXPIRED_CODE = "session_expired";
|
|
|
18
18
|
export interface RefreshableStore {
|
|
19
19
|
dispatch: (action: unknown) => unknown;
|
|
20
20
|
}
|
|
21
|
+
/** A failure that proves the session is over, as opposed to one worth retrying later. */
|
|
22
|
+
export declare class SessionEndedError extends Error {
|
|
23
|
+
constructor(message: string);
|
|
24
|
+
}
|
|
21
25
|
export declare const injectStore: <S>(_store: S) => void;
|
|
22
26
|
export declare const injectUserAuth: (options: UserAuthOptions) => void;
|
|
23
27
|
/**
|
|
@@ -59,10 +63,12 @@ export declare const waitForSessionReplacement: () => Promise<void>;
|
|
|
59
63
|
export declare const currentTokenIfReplaced: (sentToken: string | null) => Promise<string | null>;
|
|
60
64
|
/** Wait for the in-flight refresh without joining it: resolved or rejected by processQueue. */
|
|
61
65
|
export declare const queueBehindRefresh: () => Promise<string>;
|
|
66
|
+
/** True when a failure from the refresh proves the session is over (refreshAccessToken has already logged it once), as opposed to a fault worth an error line. */
|
|
67
|
+
export declare const isSessionEnd: (error: unknown) => boolean;
|
|
62
68
|
/**
|
|
63
69
|
* Stores the session a flagged request's response carries, read the way refresh responses are,
|
|
64
70
|
* before the replacement window closes, so a request waiting on the window retries with the new
|
|
65
|
-
* token. A body without tokens
|
|
71
|
+
* token. A body without tokens rejects, like a failed keychain write, so the request that carried it fails instead of resolving with a session nobody stored.
|
|
66
72
|
*/
|
|
67
73
|
export declare const storeReplacementSession: (data: unknown) => Promise<void>;
|
|
68
74
|
/**
|
|
@@ -30,6 +30,7 @@ export interface FormatCurrencyOptions extends Omit<Intl.NumberFormatOptions, "s
|
|
|
30
30
|
* its group sizes and symbol placement ("₹1.50.000,50" for `'CommaWithPointGroups'`).
|
|
31
31
|
* A numeric string reads as its number. For money the API carries in minor units (paise),
|
|
32
32
|
* use `formatMinor`.
|
|
33
|
+
* The code is not checked against the ISO 4217 list: a well-formed three-letter code the engine does not know prints as the code itself ("XYZ 1,234.00"), and only a malformed code or locale throws a RangeError.
|
|
33
34
|
*
|
|
34
35
|
* @example
|
|
35
36
|
* formatCurrency(150000, { currency: 'INR' }) // ₹1,50,000
|
|
@@ -20,6 +20,7 @@ export declare const BROADCAST_OPT_OUT_ACTION = "broadcast-opt-out";
|
|
|
20
20
|
* Wires the broadcast opt-out for this app. Call it at module scope in the entry
|
|
21
21
|
* file, before definePushActionTask from `/push/task`: a tap on a killed Android
|
|
22
22
|
* app runs that background task without the UI, so the config must already exist.
|
|
23
|
+
* It also sends again any opt-out a failed send left stored.
|
|
23
24
|
*/
|
|
24
25
|
export declare const initPushBroadcasts: (config: PushBroadcastsConfig) => void;
|
|
25
26
|
export declare const getBroadcastConsent: () => Promise<BroadcastConsent>;
|
|
@@ -28,7 +29,8 @@ export declare const withdrawBroadcastConsent: () => Promise<BroadcastConsent>;
|
|
|
28
29
|
/**
|
|
29
30
|
* Handles the opt-out button. Call it from the action handler of definePushActionTask,
|
|
30
31
|
* then run the app's own actions. Never throws: a background task has no screen to
|
|
31
|
-
* show a failure on.
|
|
32
|
+
* show a failure on. A send that fails is kept in storage and sent again at the next
|
|
33
|
+
* launch and the next opt-out. Logs never carry the token.
|
|
32
34
|
*/
|
|
33
35
|
export declare const handleBroadcastAction: PushActionHandler;
|
|
34
36
|
/**
|
|
@@ -95,6 +95,8 @@ export interface PushState {
|
|
|
95
95
|
status: PushStatus;
|
|
96
96
|
/** True once this process has registered the device, false after `disablePush` or `resetPush`. */
|
|
97
97
|
enabled: boolean;
|
|
98
|
+
/** The error from the last failed re-registration of a rotated device token, or null. Cleared when a registration succeeds and by `disablePush` and `resetPush`. `enablePush` registers on every run, so calling it again retries. */
|
|
99
|
+
registrationError: Error | null;
|
|
98
100
|
}
|
|
99
101
|
interface PermissionResponseLike {
|
|
100
102
|
status: "granted" | "denied" | "undetermined";
|
|
@@ -225,6 +227,7 @@ export declare const initPush: (next: PushConfig) => void;
|
|
|
225
227
|
* already granted registers, and any other resolves with its status
|
|
226
228
|
* (`undetermined` when the person has not been asked yet, `denied` when refused
|
|
227
229
|
* and the prompt can still show, `blocked` when only Settings can turn it on).
|
|
230
|
+
* A failed re-registration of a rotated token is logged and shown as `usePush().registrationError`.
|
|
228
231
|
*/
|
|
229
232
|
export declare const enablePush: ({ prompt }?: EnablePushOptions) => Promise<PushStatus>;
|
|
230
233
|
/** Null when push is unavailable in this build or permission is not granted. Never prompts or registers. */
|
|
@@ -9,7 +9,10 @@ export interface SecureScreenOptions {
|
|
|
9
9
|
/**
|
|
10
10
|
* Blocks capture while the calling screen is focused and releases it on blur
|
|
11
11
|
* or unmount. Each call holds its own claim, so two secure screens on the stack
|
|
12
|
-
* never release each other's protection.
|
|
12
|
+
* never release each other's protection. When blocking capture or hiding the app
|
|
13
|
+
* switcher snapshot fails, the failure is logged and the screen throws on its next
|
|
14
|
+
* render, so an error boundary shows instead of an unprotected screen. A failure
|
|
15
|
+
* to release is only logged.
|
|
13
16
|
*
|
|
14
17
|
* ```tsx
|
|
15
18
|
* import { useIsFocused } from '@react-navigation/native';
|
|
@@ -17,6 +17,7 @@ export declare const setSmsRetrieverImplementation: (impl: SmsRetrieverBackend |
|
|
|
17
17
|
* (`getAppHash`) the backend appends to the message. Android only; every
|
|
18
18
|
* method is safe to call on iOS and resolves/reports unavailable rather than
|
|
19
19
|
* throwing, so a caller doesn't need a platform check at every call site.
|
|
20
|
+
* A native listener that fails to start is reported through `onError` as `UNKNOWN_ERROR`; without an `onError` it throws.
|
|
20
21
|
*
|
|
21
22
|
* OTP extraction is left to the caller — `onMessage` receives the raw SMS
|
|
22
23
|
* text, since the expected OTP format (digit count, prefix) is a backend
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webority/mobile-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.149.0",
|
|
4
4
|
"description": "Platform layer for Webority React Native apps: HTTP clients, auth/token storage, config, logging, formatters, validators, network status, permissions, storage, version checks and over-the-air updates. No UI.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"react-native",
|
|
@@ -394,31 +394,31 @@
|
|
|
394
394
|
},
|
|
395
395
|
"peerDependencies": {
|
|
396
396
|
"@reduxjs/toolkit": "^2.12.0",
|
|
397
|
-
"expo": ">=
|
|
398
|
-
"expo-application": ">=
|
|
399
|
-
"expo-calendar": ">=
|
|
400
|
-
"expo-camera": ">=
|
|
401
|
-
"expo-clipboard": ">=
|
|
402
|
-
"expo-contacts": ">=
|
|
403
|
-
"expo-crypto": ">=
|
|
404
|
-
"expo-document-picker": ">=
|
|
405
|
-
"expo-file-system": ">=
|
|
406
|
-
"expo-image-manipulator": ">=
|
|
407
|
-
"expo-image-picker": ">=
|
|
408
|
-
"expo-local-authentication": ">=
|
|
409
|
-
"expo-location": ">=
|
|
410
|
-
"expo-media-library": ">=
|
|
411
|
-
"expo-network": ">=
|
|
412
|
-
"expo-notifications": ">=
|
|
413
|
-
"expo-screen-capture": ">=
|
|
414
|
-
"expo-secure-store": ">=
|
|
415
|
-
"expo-sharing": ">=
|
|
416
|
-
"expo-sqlite": ">=
|
|
417
|
-
"expo-store-review": ">=
|
|
418
|
-
"expo-task-manager": ">=
|
|
419
|
-
"expo-updates": ">=
|
|
420
|
-
"react": "^19.
|
|
421
|
-
"react-native": ">=0.
|
|
397
|
+
"expo": ">=58.0.0",
|
|
398
|
+
"expo-application": ">=58.0.0",
|
|
399
|
+
"expo-calendar": ">=58.0.0",
|
|
400
|
+
"expo-camera": ">=58.0.0",
|
|
401
|
+
"expo-clipboard": ">=58.0.0",
|
|
402
|
+
"expo-contacts": ">=58.0.0",
|
|
403
|
+
"expo-crypto": ">=58.0.0",
|
|
404
|
+
"expo-document-picker": ">=58.0.0",
|
|
405
|
+
"expo-file-system": ">=58.0.0",
|
|
406
|
+
"expo-image-manipulator": ">=58.0.0",
|
|
407
|
+
"expo-image-picker": ">=58.0.0",
|
|
408
|
+
"expo-local-authentication": ">=58.0.0",
|
|
409
|
+
"expo-location": ">=58.0.0",
|
|
410
|
+
"expo-media-library": ">=58.0.0",
|
|
411
|
+
"expo-network": ">=58.0.0",
|
|
412
|
+
"expo-notifications": ">=58.0.0",
|
|
413
|
+
"expo-screen-capture": ">=58.0.0",
|
|
414
|
+
"expo-secure-store": ">=58.0.0",
|
|
415
|
+
"expo-sharing": ">=58.0.0",
|
|
416
|
+
"expo-sqlite": ">=58.0.0",
|
|
417
|
+
"expo-store-review": ">=58.0.0",
|
|
418
|
+
"expo-task-manager": ">=58.0.0",
|
|
419
|
+
"expo-updates": ">=58.0.0",
|
|
420
|
+
"react": "^19.3.0",
|
|
421
|
+
"react-native": ">=0.88.0",
|
|
422
422
|
"react-redux": "^9.3.0"
|
|
423
423
|
},
|
|
424
424
|
"peerDependenciesMeta": {
|
|
@@ -511,32 +511,32 @@
|
|
|
511
511
|
]
|
|
512
512
|
},
|
|
513
513
|
"devDependencies": {
|
|
514
|
-
"@react-native/metro-config": "0.
|
|
514
|
+
"@react-native/metro-config": "0.88.1",
|
|
515
515
|
"@reduxjs/toolkit": "2.12.0",
|
|
516
516
|
"@testing-library/react-native": "12.9.0",
|
|
517
517
|
"@types/node": "25.6.0",
|
|
518
|
-
"@types/react": "19.
|
|
518
|
+
"@types/react": "19.3.0",
|
|
519
519
|
"@webority/mobile-dev": "0.0.0",
|
|
520
|
-
"expo": "
|
|
521
|
-
"expo-application": "
|
|
522
|
-
"expo-clipboard": "
|
|
523
|
-
"expo-crypto": "
|
|
524
|
-
"expo-document-picker": "
|
|
525
|
-
"expo-file-system": "
|
|
526
|
-
"expo-image-manipulator": "
|
|
527
|
-
"expo-local-authentication": "
|
|
528
|
-
"expo-location": "
|
|
529
|
-
"expo-network": "
|
|
530
|
-
"expo-screen-capture": "
|
|
531
|
-
"expo-secure-store": "
|
|
532
|
-
"expo-sqlite": "
|
|
533
|
-
"expo-store-review": "
|
|
520
|
+
"expo": "58.0.23",
|
|
521
|
+
"expo-application": "58.1.2",
|
|
522
|
+
"expo-clipboard": "58.0.4",
|
|
523
|
+
"expo-crypto": "58.0.7",
|
|
524
|
+
"expo-document-picker": "58.0.4",
|
|
525
|
+
"expo-file-system": "58.0.13",
|
|
526
|
+
"expo-image-manipulator": "58.0.16",
|
|
527
|
+
"expo-local-authentication": "58.0.2",
|
|
528
|
+
"expo-location": "58.0.20",
|
|
529
|
+
"expo-network": "58.0.4",
|
|
530
|
+
"expo-screen-capture": "58.0.6",
|
|
531
|
+
"expo-secure-store": "58.0.2",
|
|
532
|
+
"expo-sqlite": "58.0.15",
|
|
533
|
+
"expo-store-review": "58.0.2",
|
|
534
534
|
"jest": "29.7.0",
|
|
535
|
-
"react": "19.
|
|
536
|
-
"react-native": "0.
|
|
535
|
+
"react": "19.3.0",
|
|
536
|
+
"react-native": "0.88.1",
|
|
537
537
|
"react-native-builder-bob": "0.43.0",
|
|
538
538
|
"react-redux": "9.3.0",
|
|
539
|
-
"react-test-renderer": "19.
|
|
539
|
+
"react-test-renderer": "19.3.0",
|
|
540
540
|
"typescript": "5.9.3"
|
|
541
541
|
},
|
|
542
542
|
"scripts": {
|