@webority/mobile-core 0.1.0 → 0.2.1
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/README.md +32 -0
- package/lib/commonjs/api/clientHeaders.js +1 -0
- package/lib/commonjs/api/minAppVersion.js +1 -0
- package/lib/commonjs/api/publicClient.js +1 -1
- package/lib/commonjs/api/requestDefaults.js +1 -0
- 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/auth/index.js +1 -1
- package/lib/commonjs/config/index.js +1 -1
- package/lib/commonjs/errors/extractApiError.js +1 -0
- package/lib/commonjs/errors/index.js +1 -0
- package/lib/commonjs/formatters/currency.js +1 -1
- package/lib/commonjs/formatters/date.js +1 -1
- package/lib/commonjs/formatters/dateMath.js +1 -1
- package/lib/commonjs/formatters/formatConfig.js +1 -0
- package/lib/commonjs/formatters/house.js +1 -0
- package/lib/commonjs/formatters/index.js +1 -1
- package/lib/commonjs/formatters/number.js +1 -1
- package/lib/commonjs/index.js +1 -1
- package/lib/commonjs/initSDK.js +1 -1
- package/lib/commonjs/initUserAuth.js +1 -1
- package/lib/commonjs/logger/index.js +1 -1
- package/lib/commonjs/query/apiBaseQuery.js +1 -0
- package/lib/commonjs/query/createAppApi.js +1 -0
- package/lib/commonjs/query/index.js +1 -0
- package/lib/commonjs/query/listeners.js +1 -0
- package/lib/commonjs/query/paging.js +1 -0
- package/lib/commonjs/query/tags.js +1 -0
- package/lib/commonjs/redux/errorToastMiddleware.js +1 -0
- package/lib/commonjs/redux/index.js +1 -0
- package/lib/commonjs/redux/rootReducer.js +1 -0
- package/lib/commonjs/redux/serializableCheck.js +1 -0
- package/lib/commonjs/versionCheck/buildNumber.js +1 -0
- package/lib/commonjs/versionCheck/index.js +1 -1
- package/lib/module/api/baseUrl.js +1 -1
- package/lib/module/api/clientHeaders.js +1 -0
- package/lib/module/api/curl.js +1 -1
- package/lib/module/api/minAppVersion.js +1 -0
- package/lib/module/api/multipart.js +1 -1
- package/lib/module/api/publicClient.js +1 -1
- package/lib/module/api/requestDefaults.js +1 -0
- package/lib/module/api/responseBodyText.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/auth/index.js +1 -1
- package/lib/module/auth/jwt.js +1 -1
- package/lib/module/config/index.js +1 -1
- package/lib/module/deepLink/index.js +1 -1
- package/lib/module/download/adapters/expoFs.js +1 -1
- package/lib/module/download/adapters/shared.js +1 -1
- package/lib/module/download/index.js +1 -1
- package/lib/module/errors/extractApiError.js +1 -0
- package/lib/module/errors/index.js +1 -0
- package/lib/module/formatters/currency.js +1 -1
- package/lib/module/formatters/date.js +1 -1
- package/lib/module/formatters/dateMath.js +1 -1
- package/lib/module/formatters/formatConfig.js +1 -0
- package/lib/module/formatters/house.js +1 -0
- package/lib/module/formatters/index.js +1 -1
- package/lib/module/formatters/initials.js +1 -1
- package/lib/module/formatters/intlCache.js +1 -1
- package/lib/module/formatters/number.js +1 -1
- package/lib/module/formatters/phone.js +1 -1
- package/lib/module/formatters/windowsToIanaTable.js +1 -1
- package/lib/module/geolocation/adapters/expoLocation.js +1 -1
- package/lib/module/geolocation/index.js +1 -1
- package/lib/module/index.js +1 -1
- package/lib/module/initSDK.js +1 -1
- package/lib/module/initUserAuth.js +1 -1
- package/lib/module/logger/crashlytics.js +1 -1
- package/lib/module/logger/index.js +1 -1
- package/lib/module/logger/redact.js +1 -1
- package/lib/module/network/index.js +1 -1
- package/lib/module/network/networkStatus.js +1 -1
- package/lib/module/permissions/calendar.js +1 -1
- package/lib/module/permissions/camera.js +1 -1
- package/lib/module/permissions/contacts.js +1 -1
- package/lib/module/permissions/index.js +1 -1
- package/lib/module/permissions/location.js +1 -1
- package/lib/module/permissions/mediaLibrary.js +1 -1
- package/lib/module/permissions/notifications.js +1 -1
- package/lib/module/permissions/photos.js +1 -1
- package/lib/module/phone/countries.js +1 -1
- package/lib/module/push/index.js +1 -1
- package/lib/module/push/push.js +1 -1
- package/lib/module/push/status.js +1 -1
- package/lib/module/push/task.js +1 -1
- package/lib/module/query/apiBaseQuery.js +1 -0
- package/lib/module/query/createAppApi.js +1 -0
- package/lib/module/query/index.js +1 -0
- package/lib/module/query/listeners.js +1 -0
- package/lib/module/query/paging.js +1 -0
- package/lib/module/query/tags.js +1 -0
- package/lib/module/redux/errorToastMiddleware.js +1 -0
- package/lib/module/redux/index.js +1 -0
- package/lib/module/redux/rootReducer.js +1 -0
- package/lib/module/redux/serializableCheck.js +1 -0
- package/lib/module/secureScreen/index.js +1 -1
- package/lib/module/share/index.js +1 -1
- package/lib/module/smsRetriever/index.js +1 -1
- package/lib/module/specs/NativeSmsRetriever.js +1 -1
- package/lib/module/sqlite/adapters/expo.js +1 -1
- package/lib/module/sqlite/index.js +1 -1
- package/lib/module/storage/index.js +1 -1
- package/lib/module/types/axios.js +1 -1
- package/lib/module/types/globals.d.js +1 -1
- package/lib/module/utils/base64.js +1 -1
- package/lib/module/utils/imageCompression.js +1 -1
- package/lib/module/utils/index.js +1 -1
- package/lib/module/validators/index.js +1 -1
- package/lib/module/versionCheck/buildNumber.js +1 -0
- package/lib/module/versionCheck/index.js +1 -1
- package/lib/typescript/commonjs/api/clientHeaders.d.ts +25 -0
- package/lib/typescript/commonjs/api/minAppVersion.d.ts +24 -0
- package/lib/typescript/commonjs/api/requestDefaults.d.ts +21 -0
- package/lib/typescript/commonjs/api/retry.d.ts +23 -9
- package/lib/typescript/commonjs/api/tokenRefresh.d.ts +14 -2
- package/lib/typescript/commonjs/api/userClient.d.ts +1 -1
- package/lib/typescript/commonjs/auth/authStore.d.ts +76 -0
- package/lib/typescript/commonjs/auth/index.d.ts +2 -2
- package/lib/typescript/commonjs/config/index.d.ts +31 -2
- package/lib/typescript/commonjs/errors/extractApiError.d.ts +69 -0
- package/lib/typescript/commonjs/errors/index.d.ts +3 -0
- package/lib/typescript/commonjs/formatters/currency.d.ts +22 -7
- package/lib/typescript/commonjs/formatters/date.d.ts +13 -13
- package/lib/typescript/commonjs/formatters/dateMath.d.ts +4 -2
- package/lib/typescript/commonjs/formatters/formatConfig.d.ts +48 -0
- package/lib/typescript/commonjs/formatters/house.d.ts +143 -0
- package/lib/typescript/commonjs/formatters/index.d.ts +4 -0
- package/lib/typescript/commonjs/formatters/number.d.ts +15 -5
- package/lib/typescript/commonjs/index.d.ts +21 -8
- package/lib/typescript/commonjs/initSDK.d.ts +18 -6
- package/lib/typescript/commonjs/initUserAuth.d.ts +29 -0
- package/lib/typescript/commonjs/logger/index.d.ts +17 -0
- package/lib/typescript/commonjs/query/apiBaseQuery.d.ts +55 -0
- package/lib/typescript/commonjs/query/createAppApi.d.ts +21 -0
- package/lib/typescript/commonjs/query/index.d.ts +9 -0
- package/lib/typescript/commonjs/query/listeners.d.ts +11 -0
- package/lib/typescript/commonjs/query/paging.d.ts +42 -0
- package/lib/typescript/commonjs/query/tags.d.ts +31 -0
- package/lib/typescript/commonjs/redux/errorToastMiddleware.d.ts +51 -0
- package/lib/typescript/commonjs/redux/index.d.ts +6 -0
- package/lib/typescript/commonjs/redux/rootReducer.d.ts +19 -0
- package/lib/typescript/commonjs/redux/serializableCheck.d.ts +14 -0
- package/lib/typescript/commonjs/versionCheck/buildNumber.d.ts +14 -0
- package/lib/typescript/commonjs/versionCheck/index.d.ts +28 -17
- package/lib/typescript/module/api/clientHeaders.d.ts +25 -0
- package/lib/typescript/module/api/minAppVersion.d.ts +24 -0
- package/lib/typescript/module/api/requestDefaults.d.ts +21 -0
- package/lib/typescript/module/api/retry.d.ts +23 -9
- package/lib/typescript/module/api/tokenRefresh.d.ts +14 -2
- package/lib/typescript/module/api/userClient.d.ts +1 -1
- package/lib/typescript/module/auth/authStore.d.ts +76 -0
- package/lib/typescript/module/auth/index.d.ts +2 -2
- package/lib/typescript/module/config/index.d.ts +31 -2
- package/lib/typescript/module/errors/extractApiError.d.ts +69 -0
- package/lib/typescript/module/errors/index.d.ts +3 -0
- package/lib/typescript/module/formatters/currency.d.ts +22 -7
- package/lib/typescript/module/formatters/date.d.ts +13 -13
- package/lib/typescript/module/formatters/dateMath.d.ts +4 -2
- package/lib/typescript/module/formatters/formatConfig.d.ts +48 -0
- package/lib/typescript/module/formatters/house.d.ts +143 -0
- package/lib/typescript/module/formatters/index.d.ts +4 -0
- package/lib/typescript/module/formatters/number.d.ts +15 -5
- package/lib/typescript/module/index.d.ts +21 -8
- package/lib/typescript/module/initSDK.d.ts +18 -6
- package/lib/typescript/module/initUserAuth.d.ts +29 -0
- package/lib/typescript/module/logger/index.d.ts +17 -0
- package/lib/typescript/module/query/apiBaseQuery.d.ts +55 -0
- package/lib/typescript/module/query/createAppApi.d.ts +21 -0
- package/lib/typescript/module/query/index.d.ts +9 -0
- package/lib/typescript/module/query/listeners.d.ts +11 -0
- package/lib/typescript/module/query/paging.d.ts +42 -0
- package/lib/typescript/module/query/tags.d.ts +31 -0
- package/lib/typescript/module/redux/errorToastMiddleware.d.ts +51 -0
- package/lib/typescript/module/redux/index.d.ts +6 -0
- package/lib/typescript/module/redux/rootReducer.d.ts +19 -0
- package/lib/typescript/module/redux/serializableCheck.d.ts +14 -0
- package/lib/typescript/module/versionCheck/buildNumber.d.ts +14 -0
- package/lib/typescript/module/versionCheck/index.d.ts +28 -17
- package/package.json +30 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=exports.VersionCheck=void 0,Object.defineProperty(exports,"isBuildBelowMinimum",{enumerable:!0,get:function(){return _buildNumber.isBuildBelowMinimum}}),Object.defineProperty(exports,"parseBuildNumber",{enumerable:!0,get:function(){return _buildNumber.parseBuildNumber}}),exports.useVersionCheck=exports.setDeviceInfoImplementation=void 0;var Application=_interopRequireWildcard(require("expo-application")),_react=require("react"),_minAppVersion=require("../api/minAppVersion.js"),_index=require("../config/index.js"),_index2=require("../logger/index.js"),_buildNumber=require("./buildNumber.js");function _interopRequireWildcard(e,r){if("function"==typeof WeakMap)var i=new WeakMap,t=new WeakMap;return(_interopRequireWildcard=function(e,r){if(!r&&e&&e.__esModule)return e;var n,o,l={__proto__:null,default:e};if(null===e||"object"!=typeof e&&"function"!=typeof e)return l;if(n=r?t:i){if(n.has(e))return n.get(e);n.set(e,l)}for(const r in e)"default"!==r&&{}.hasOwnProperty.call(e,r)&&((o=(n=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,r))&&(o.get||o.set)?n(l,r,o):l[r]=e[r]);return l})(e,r)}const expoApplicationBackend={getBundleId:()=>Application.applicationId??"",getVersion:()=>Application.nativeApplicationVersion??"",getBuildNumber:()=>Application.nativeBuildVersion??""};let deviceInfo=null;const setDeviceInfoImplementation=e=>{deviceInfo=e};exports.setDeviceInfoImplementation=setDeviceInfoImplementation;const missing=(e,r)=>{const i=new Error(`[VersionCheck] the app's ${e} is not available. Call setConfig({ ${r}: ... }) — every Webority app already has this value in appsettings.Compiled.json — or setDeviceInfoImplementation() with a native provider.`);return _index2.Logger.error(i.message),i},getSystemName=()=>{const{Platform:e}=require("react-native");return e.OS},getBundleId=()=>{const e=(0,_index.getConfigValue)("appId");if(e)return e;const r=(deviceInfo??expoApplicationBackend).getBundleId();if(r)return r;throw missing("store identifier","appId")},getBuildNumber=()=>{const e=(0,_buildNumber.parseBuildNumber)((0,_index.getConfigValue)("appBuild"));if(null!==e)return e;const r=(0,_buildNumber.parseBuildNumber)(deviceInfo?.getBuildNumber?.()??expoApplicationBackend.getBuildNumber());if(null!==r)return r;throw missing("build number","appBuild")},getCountry=()=>(0,_index.getConfigValue)("country","in").toLowerCase(),subscribeMinimum=e=>(0,_minAppVersion.addMinAppVersionListener)(()=>e()),getFallbackStoreUrl=()=>{const e=getSystemName().toLowerCase(),r=getCountry();if("ios"===e){const e=(0,_index.getConfigValue)("appStoreId");return e?`https://apps.apple.com/${r}/app/id${e}`:`https://apps.apple.com/${r}/app/${getBundleId()}`}return`https://play.google.com/store/apps/details?id=${getBundleId()}&hl=${r}`},storeUrlOrNull=()=>{try{return getFallbackStoreUrl()}catch{return null}},checkForUpdates=()=>{const e=(0,_buildNumber.isBuildBelowMinimum)(getBuildNumber(),(0,_minAppVersion.getMinAppVersion)());return{isNewVersionAvailable:e,updateType:e?"major":null,url:e?storeUrlOrNull():null}},VersionCheck=exports.VersionCheck={isNewVersionAvailable:async()=>checkForUpdates(),openUpdateUrl:async e=>{const{Linking:r}=require("react-native");try{if(e)_index2.Logger.info(`Opening app store URL: ${e}`),await r.openURL(e);else{const e=getFallbackStoreUrl();_index2.Logger.info(`Opening fallback store URL: ${e}`),await r.openURL(e)}return!0}catch(i){const t=i instanceof Error?i.message:String(i);_index2.Logger.error(`Failed to open store URL: ${t}`);try{if(e){const e=getFallbackStoreUrl();return _index2.Logger.info(`Trying fallback store URL: ${e}`),await r.openURL(e),!0}}catch(e){const r=e instanceof Error?e.message:String(e);_index2.Logger.error(`Failed to open fallback URL: ${r}`)}return!1}},getFallbackStoreUrl:getFallbackStoreUrl},NOT_REQUIRED={isUpdateRequired:!1,updateUrl:null},useVersionCheck=(e,r=(0,_index.getConfigValue)("environment","Development"))=>{const i=(0,_react.useSyncExternalStore)(subscribeMinimum,_minAppVersion.getMinAppVersion,_minAppVersion.getMinAppVersion);return(0,_react.useMemo)(()=>{if(!e||"Production"!==r||null===i)return NOT_REQUIRED;try{if(!(0,_buildNumber.isBuildBelowMinimum)(getBuildNumber(),i))return NOT_REQUIRED}catch{return NOT_REQUIRED}return{isUpdateRequired:!0,updateUrl:storeUrlOrNull()}},[e,r,i])};exports.useVersionCheck=useVersionCheck;var _default=exports.default=VersionCheck;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getConfigValue
|
|
1
|
+
"use strict";import{getConfigValue}from"../config/index.js";export const applyConfiguredBaseUrl=e=>{e.interceptors.request.use(e=>(e.baseURL||(e.baseURL=getConfigValue("baseUrl")??void 0),e))};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";import{getConfigValue}from"../config/index.js";export const CLIENT_BUILD_HEADER="X-Client-Build";export const CLIENT_KIND_HEADER="X-Client-Kind";export const ACCOUNT_ID_HEADER="X-Account-Id";export const CLIENT_KIND="MobileApp";export const getClientBuild=()=>{const t=getConfigValue("appVersion");if(!t)return null;const e=getConfigValue("commit");return e?`${t}+${e}`:t};const setIfAbsent=(t,e,n)=>{n&&!t.has(e)&&t.set(e,n)};export const applyClientHeaders=t=>{t.interceptors.request.use(t=>(setIfAbsent(t.headers,"X-Client-Kind","MobileApp"),setIfAbsent(t.headers,"X-Client-Build",getClientBuild()),t))};export const applyAccountIdHeader=async(t,e)=>{const n=e?await e():null;n&&t.set("X-Account-Id",n)};
|
package/lib/module/api/curl.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Logger
|
|
1
|
+
"use strict";import{Logger}from"../logger/index.js";const SECRET_HEADERS=new Set(["authorization","proxy-authorization","cookie","set-cookie","x-api-key","x-auth-token","x-access-token","x-refresh-token","api-key"]),SECRET_BODY_PATTERN=/pass(word|code)|secret|token|otp|pin|cvv|authoriz/i,AXIOS_METHOD_KEYS=new Set(["common","delete","get","head","post","put","patch"]),REDACTED="<redacted>",redactBody=(t,e,r=0)=>{if(null===t||"object"!=typeof t)return t;if(e.has(t))return"<circular>";if(r>6)return"<truncated>";if(e.add(t),Array.isArray(t))return t.map(t=>redactBody(t,e,r+1));const o={};for(const[a,n]of Object.entries(t))o[a]=SECRET_BODY_PATTERN.test(a)?REDACTED:redactBody(n,e,r+1);return o},buildUrl=t=>{const e=t.url??"",r=t.baseURL?t.baseURL.replace(/\/$/,""):"";let o=e.startsWith("http")?e:`${r}/${e.replace(/^\//,"")}`;if(t.params){const e=new URLSearchParams(t.params).toString();e&&(o+=(o.includes("?")?"&":"?")+e)}return o};export const buildCurl=t=>{let e=`curl -X ${(t.method??"get").toUpperCase()} "${buildUrl(t)}"`;const r=t.headers;if(r)for(const[t,o]of Object.entries(r)){if(AXIOS_METHOD_KEYS.has(t))continue;if("string"!=typeof o&&"number"!=typeof o)continue;const r=SECRET_HEADERS.has(t.toLowerCase())?REDACTED:o;e+=` -H "${t}: ${r}"`}if(void 0!==t.data&&null!==t.data){const r="object"==typeof t.data?redactBody(t.data,new WeakSet):t.data;e+=` -d '${("object"==typeof r?JSON.stringify(r):String(r)).replace(/'/g,"'\\''")}'`}return e};export const logCurl=t=>{try{Logger.info("CURL Command:",buildCurl(t))}catch(t){Logger.warn("[api] Failed to build a curl command for the request",t)}};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";import{Logger}from"../logger/index.js";export const MIN_APP_VERSION_HEADER="X-Min-App-Version";let current=null;const listeners=new Set;export const getMinAppVersion=()=>current;export const addMinAppVersionListener=e=>(listeners.add(e),null!==current&&e(current),()=>{listeners.delete(e)});const readHeader=e=>{if(!e||"object"!=typeof e)return;const r=e.get;return"function"==typeof r?r.call(e,"X-Min-App-Version"):e["X-Min-App-Version".toLowerCase()]},record=e=>{const r=readHeader(e?.headers);if(null==r||""===r)return;const n=String(r).trim();if(!/^\d+$/.test(n))return void Logger.warn(`[minAppVersion] ignored a non-integer X-Min-App-Version: ${n}`);const t=Number.parseInt(n,10);if(t!==current){current=t;for(const e of[...listeners])try{e(t)}catch(e){Logger.error("[minAppVersion] a listener threw",e)}}};export const readMinAppVersion=e=>{e.interceptors.response.use(e=>(record(e),e),e=>(record(e?.response),Promise.reject(e)))};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export const sendFormDataAsMultipart=e=>{e.interceptors.request.use(e=>("undefined"!=typeof FormData&&e.data instanceof FormData&&e.headers?.delete?.("Content-Type"),e))};
|
|
1
|
+
"use strict";export const sendFormDataAsMultipart=e=>{e.interceptors.request.use(e=>("undefined"!=typeof FormData&&e.data instanceof FormData&&e.headers?.delete?.("Content-Type"),e))};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
"use strict";import axios from"axios";import{getConfigValue}from"../config/index.js";import{Logger}from"../logger/index.js";import"../types/axios.js";import{applyConfiguredBaseUrl}from"./baseUrl.js";import{applyClientHeaders}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";const publicClient=axios.create({headers:{"Content-Type":"application/json",Accept:"application/json"}});applyConfiguredBaseUrl(publicClient),applyRequestDefaults(publicClient),sendFormDataAsMultipart(publicClient),readMinAppVersion(publicClient),attachRetry(publicClient),publicClient.interceptors.request.use(e=>(Logger.info(`Request: ${e.method?.toUpperCase()} ${e.url}`),getConfigValue("logCurl")&&logCurl(e),e),e=>{const r=e instanceof Error?e.message:String(e);return Logger.error("Request error:",r),Promise.reject(e)}),applyClientHeaders(publicClient),publicClient.interceptors.response.use(e=>(Logger.info(`Response: ${e.status} from ${e.config.url}`),e),e=>{if(axios.isAxiosError(e)){const r=e.config;if(r?.skipErrorLog)return Promise.reject(e);e.response?Logger.error(`Response error: ${responseBodyText(e.response.data,e.message)}, URL: ${r?.url}, Status: ${e.response.status}`):Logger.error(`Network error or no response from server: ${e.message}, URL: ${r?.url}`)}else{const r=e instanceof Error?e.message:String(e);Logger.error(`Unknown response error: ${r}`)}return Promise.reject(e)});export default publicClient;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";import{getConfigValue}from"../config/index.js";export const newCorrelationId=()=>{const e=globalThis.crypto;if("function"==typeof e?.randomUUID)return e.randomUUID();const t=new Uint8Array(16);if("function"==typeof e?.getRandomValues)e.getRandomValues(t);else for(let e=0;e<t.length;e+=1)t[e]=Math.floor(256*Math.random());t[6]=15&(t[6]??0)|64,t[8]=63&(t[8]??0)|128;const o=Array.from(t,e=>e.toString(16).padStart(2,"0")).join("");return`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`};export const applyRequestDefaults=e=>{e.defaults.timeout=void 0,e.interceptors.request.use(e=>{void 0===e.timeout&&(e.timeout=getConfigValue("timeoutMs"));const t=getConfigValue("correlationIdHeader");return t&&!e.headers.has(t)&&e.headers.set(t,newCorrelationId()),e})};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export const responseBodyText=(e,n)=>{if(null==e||""===e)return n;if(e instanceof ArrayBuffer)return`binary response (${e.byteLength} bytes)`;if("undefined"!=typeof Blob&&e instanceof Blob)return`binary response (${e.size} bytes)`;const
|
|
1
|
+
"use strict";const MAX_LENGTH=500;export const responseBodyText=(e,n)=>{if(null==e||""===e)return n;if(e instanceof ArrayBuffer)return`binary response (${e.byteLength} bytes)`;if("undefined"!=typeof Blob&&e instanceof Blob)return`binary response (${e.size} bytes)`;const t="string"==typeof e?e:JSON.stringify(e);return t.length>500?`${t.slice(0,500)}...`:t};
|
package/lib/module/api/retry.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const isRetryableStatus=e=>"number"==typeof e&&(429===e||e>=500&&e<=599);const
|
|
1
|
+
"use strict";import axios from"axios";import{getConfigValue}from"../config/index.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"]),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.data,o=t.headers,s="function"==typeof o?.get?o.get("retry-after"):o?.["retry-after"];for(const e of[r?.retryAfterSeconds,s]){const t=Number(e);if(null!=e&&Number.isFinite(t)&&t>0)return 1e3*t}return 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 isRetryableFailure=e=>{if(axios.isCancel(e)||"ERR_CANCELED"===e.code)return!1;if(isNeverSentError(e))return!0;const t=(e.config?.method??"get").toLowerCase(),r=IDEMPOTENT_METHODS.has(t),o=e.response?.status;if(void 0===o)return r;if(!isRetryableStatus(o))return!1;const s=retryAfterMs(e);return!(null!==s&&s>3e4)&&(r||(429===o||503===o)&&hasIdempotencyKey(e.config))};const DEFAULT_POLICY={retryDelayMs:e=>e<=1?0:2**e*1e3,shouldRetry:isRetryableFailure,onRetry:()=>{}},waitOrAbort=(e,t)=>new Promise(r=>{const onAbort=()=>{clearTimeout(o),r(!1)},o=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 o=r,s=o?.config;if(!s||!1===s.retry)return Promise.reject(r);const n="object"==typeof s.retry?s.retry:{},i={...DEFAULT_POLICY,retries:getConfigValue("retries"),...t,...n},c=(s.__retryAttempt??0)+1;if(c>i.retries||!i.shouldRetry(o))return Promise.reject(r);if(s.signal?.aborted)return Promise.reject(r);s.__retryAttempt=c,s.transformRequest=[e=>e],i.onRetry(c,o);const a=retryAfterMs(o)??i.retryDelayMs(c);return await waitOrAbort(a,s.signal)?e.request(s):Promise.reject(r)})};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
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";let store,auth;export const injectStore=e=>{store=e};export const injectUserAuth=e=>{auth=e};let refreshTokenPromise=null,failedQueue=[];const processQueue=(e,r=null)=>{failedQueue.forEach(({resolve:o,reject:s})=>{e?s(e):null!==r&&o(r)}),failedQueue=[]};export const resetRefreshState=()=>{refreshTokenPromise=null,processQueue(new Error("[@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 SIGN_OUT_REASON_HEADER="X-Sign-Out-Reason";export const readSignOutReason=e=>{const r=void 0===auth?.signOutReasonHeader?"X-Sign-Out-Reason":auth.signOutReasonHeader;if(!r||!e||"object"!=typeof e)return null;const o=e.get,s="function"==typeof o?o.call(e,r):e[r.toLowerCase()];return"string"==typeof s&&""!==s.trim()?s.trim():null};export const endSessionAndLogout=async(e,r)=>{await clearSession(e,{signOutReason:r}),await dispatchLogout()};export const isRefreshInFlight=()=>null!==refreshTokenPromise;export const queueBehindRefresh=()=>new Promise((e,r)=>{failedQueue.push({resolve:e,reject:r})});class SessionEndedError extends Error{constructor(e){super(e),this.name="SessionEndedError",Object.setPrototypeOf(this,SessionEndedError.prototype)}}const endsSession=e=>e instanceof SessionEndedError||axios.isAxiosError(e)&&(400===e.response?.status||401===e.response?.status),asString=(e,r)=>{if("string"!=typeof e||""===e)throw new Error(`The refresh response has no "${r}".`);return e},readWeborityTokens=e=>{const r=e??{};return{accessToken:asString(r.accessToken,"accessToken"),accessTokenExpiry:asString(r.accessTokenExpiration,"accessTokenExpiration"),refreshToken:asString(r.refreshToken,"refreshToken"),refreshTokenExpiry:asString(r.refreshTokenExpiration,"refreshTokenExpiration")}},callRefreshEndpoint=async e=>{const r=await getToken(REFRESH_TOKEN_KEY);if(!r?.token)throw new SessionEndedError("No refresh token available");if(Date.parse(r.expiry)<=Date.now())throw new SessionEndedError("Refresh token expired");const o=await getToken(ACCESS_TOKEN_KEY),s={accessToken:o?.token??null,refreshToken:r.token},t=e.body?await e.body(s):s,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}:void 0),a=(e.readTokens??readWeborityTokens)(i);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};export const refreshAccessToken=()=>{if(refreshTokenPromise)return refreshTokenPromise;const e=(async()=>{try{const e=await callRefreshEndpoint(requireAuth().auth.refresh);return processQueue(null,e),e}catch(e){const r=axios.isAxiosError(e)?e.response?.data:void 0;throw Logger.error("Token refresh failed:",r??getErrorMessage(e)),processQueue(e,null),endsSession(e)&&await endSessionAndLogout("rejected",axios.isAxiosError(e)?readSignOutReason(e.response?.headers):null),e}})().finally(()=>{refreshTokenPromise===e&&(refreshTokenPromise=null)});return refreshTokenPromise=e,e};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
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{applyAccountIdHeader,applyClientHeaders}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{endSessionAndLogout,getAccountIdProvider,getErrorMessage,getRefreshPath,isRefreshInFlight,queueBehindRefresh,readSignOutReason,refreshAccessToken,resetRefreshState}from"./tokenRefresh.js";export{injectStore,injectUserAuth,resetRefreshState,SIGN_OUT_REASON_HEADER}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)}}export const SESSION_TERMINATION_CODES={TERMINATED:"SESSION_TERMINATED",EXPIRED:"SESSION_EXPIRED"};const TERMINATION_CODES=new Set(Object.values(SESSION_TERMINATION_CODES));export const SESSION_INVALID_HEADER="x-security-stamp-invalid";const hasSessionInvalidHeader=e=>{if(!e||"object"!=typeof e)return!1;const r=e.get,t="function"==typeof r?r.call(e,SESSION_INVALID_HEADER):e[SESSION_INVALID_HEADER];return"true"===String(t).toLowerCase()},getSessionTerminationCode=e=>{if(!e||"object"!=typeof e)return;const r=e,t=r.error,s=[r.code,r.errorCode,t&&"object"==typeof t?t.code:void 0];for(const e of s)if("string"==typeof e&&TERMINATION_CODES.has(e))return e},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)};applyConfiguredBaseUrl(userClient),applyRequestDefaults(userClient),sendFormDataAsMultipart(userClient),userClient.interceptors.request.use(e=>(getConfigValue("logCurl")&&logCurl(e),e)),applyClientHeaders(userClient),userClient.interceptors.request.use(async 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;const r=await getToken(ACCESS_TOKEN_KEY);if(!r?.token)throw new Error("No access token available");const t=Date.now(),s=Date.parse(r.expiry);if(s<=t+3e4){Logger.info("Access token expired or about to expire, refreshing before request");const r=await refreshAccessToken();return setAuthHeader(e,r),await applyAccountIdHeader(e.headers,getAccountIdProvider()),e}return setAuthHeader(e,r.token),await applyAccountIdHeader(e.headers,getAccountIdProvider()),e}catch(e){return Logger.error("Failed to attach token:",getErrorMessage(e)),Promise.reject(e)}},e=>(Logger.error("Request error:",getErrorMessage(e)),Promise.reject(e))),userClient.interceptors.response.use(e=>e,async e=>{if(!axios.isAxiosError(e))return Logger.error(`Non-axios error in response interceptor: ${getErrorMessage(e)}`),Promise.reject(e);const r=e,t=r.config;if(!r.response)return t?.skipErrorLog||Logger.error(`Network error or no response from server: ${r.message}, URL: ${t?.url}`),Promise.reject(e);if(401===r.response.status&&t&&!t._retry){if(isRefreshTokenRequest(t.url))return Promise.reject(e);const s=readSignOutReason(r.response.headers),o=getSessionTerminationCode(r.response.data)??(hasSessionInvalidHeader(r.response.headers)||null!==s?SESSION_TERMINATION_CODES.TERMINATED:void 0);if(o)return Logger.warn(`Session ${o}, logging out without refresh. URL: ${t.url}`),resetRefreshState(),await endSessionAndLogout("terminated",s),Promise.reject(e);if(Logger.warn(`Unauthorized URL: ${t.url}`),t._retry=!0,isRefreshInFlight())return queueBehindRefresh().then(e=>(Logger.info("Retrying request after token refresh:",t.url),setAuthHeader(t,e),userClient(t))).catch(e=>(Logger.error("Failed to retry request after token refresh:",getErrorMessage(e)),Promise.reject(e)));try{const e=await refreshAccessToken();return setAuthHeader(t,e),userClient(t)}catch(e){return Promise.reject(e)}}return t?.skipErrorLog||Logger.error(`Response error: ${responseBodyText(r.response?.data,r.message)}, URL: ${t?.url}, Status: ${r.response.status}`),Promise.reject(e)});export default userClient;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as
|
|
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(),o=!await r.getGenericPassword({service:"accessToken"})&&!await r.getGenericPassword({service:"refreshToken"}),t=await readLegacyRaw(e.accessToken),n=await readLegacyRaw(e.refreshToken);if(o&&(null!==t||null!==n)){const o=null===t?null:readLegacyToken(t),s=null===n?null:readLegacyToken(n);if(o){const e=o.expiry??expiryOf(o.token)??(new Date).toISOString();await r.setGenericPassword("token",JSON.stringify({token:o.token,expiry:e}),{service:"accessToken"})}if(s){const e=s.expiry??expiryOf(s.token)??new Date(Date.now()+2592e6).toISOString();await r.setGenericPassword("token",JSON.stringify({token:s.token,expiry:e}),{service:"refreshToken"})}if(e.sessionUser){const r=await Storage.getItem(e.sessionUser);null!==r&&await Storage.setItem("sessionUser",r)}null===o&&null===s||(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&&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)=>{const t=r||null!==await getToken("accessToken")||null!==await getToken("refreshToken");await removeToken("accessToken"),await removeToken("refreshToken"),await removeSessionUser(),t&&emitSessionEnded(e,{signOutReason:o})};export const clearSession=async(e="signedOut",r={})=>endSession(e,!1,r.signOutReason??null);
|
package/lib/module/auth/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{getToken,removeToken,storeToken}from"./authStore.js";export{decodeJWT,getJWTExpiry,isJWTExpired}from"./jwt.js";
|
|
1
|
+
"use strict";export{ACCESS_TOKEN_KEY,addSessionEndedListener,clearSession,getSessionUser,getToken,LEGACY_REFRESH_TOKEN_LIFETIME_MS,REFRESH_TOKEN_KEY,removeSessionUser,removeToken,SESSION_USER_KEY,setLegacyTokenKeys,storeSessionUser,storeToken}from"./authStore.js";export{decodeJWT,getJWTExpiry,isJWTExpired}from"./jwt.js";
|
package/lib/module/auth/jwt.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Logger
|
|
1
|
+
"use strict";import{Logger}from"../logger/index.js";const base64UrlToBase64=e=>(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),BASE64_ALPHABET="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",decodeBase64Fallback=e=>{let t="";for(let r=0;r<e.length;r+=4){const o=[0,1,2,3].map(t=>BASE64_ALPHABET.indexOf(e[r+t]??"=")),n=Math.max(o[0],0)<<18|Math.max(o[1],0)<<12|Math.max(o[2],0)<<6|Math.max(o[3],0);t+=String.fromCharCode(n>>16&255),-1!==o[2]&&(t+=String.fromCharCode(n>>8&255)),-1!==o[3]&&(t+=String.fromCharCode(255&n))}return t},decodeBase64=e=>"function"==typeof atob?atob(e):decodeBase64Fallback(e),utf8FromBinary=e=>{try{return decodeURIComponent(e.split("").map(e=>"%"+e.charCodeAt(0).toString(16).padStart(2,"0")).join(""))}catch{return e}};export const decodeJWT=e=>{if(!e||"string"!=typeof e)return null;const t=e.split(".");if(3!==t.length)return Logger.warn("[jwt] decodeJWT: token is not a valid JWT (expected 3 segments)"),null;try{const e=t[1],r=utf8FromBinary(decodeBase64(base64UrlToBase64(e)));return JSON.parse(r)}catch(e){return Logger.warn("[jwt] decodeJWT failed to parse payload",e),null}};export const isJWTExpired=(e,t=30)=>{const r=decodeJWT(e);if(!r||"number"!=typeof r.exp)return!0;const o=Math.floor(Date.now()/1e3);return r.exp<=o+t};export const getJWTExpiry=e=>{const t=decodeJWT(e);return t&&"number"==typeof t.exp?new Date(1e3*t.exp):null};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export const DEFAULT_LOG_LEVEL=__DEV__?"info":"warn";const
|
|
1
|
+
"use strict";export const DEFAULT_LOG_LEVEL=__DEV__?"info":"warn";export const DEFAULT_TIMEOUT_MS=3e4;export const DEFAULT_RETRIES=3;export const DEFAULT_CORRELATION_ID_HEADER="X-Correlation-Id";const DEFAULT_CONFIG={baseUrl:null,loggingEnabled:!0,logLevel:DEFAULT_LOG_LEVEL,environment:"Development",country:"in",appId:null,appVersion:null,commit:null,appBuild:null,appStoreId:null,logCurl:!1,timeoutMs:3e4,retries:3,correlationIdHeader:"X-Correlation-Id"};let globalConfig={...DEFAULT_CONFIG};export const setConfig=o=>{globalConfig={...globalConfig,...o}};export const getConfig=()=>globalConfig;export function getConfigValue(o,n){const l=globalConfig[o];return null!==l?l:n}export const resetConfig=()=>{globalConfig={...DEFAULT_CONFIG}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{useEffect
|
|
1
|
+
"use strict";import{useEffect,useRef}from"react";import{Linking}from"react-native";import{Logger}from"../logger/index.js";const PREFIX="[@webority/mobile-core]",decodeSafe=e=>{try{return decodeURIComponent(e.replace(/\+/g," "))}catch{return e}},parseQuery=e=>{const t={};if(!e)return t;for(const n of e.split("&")){if(!n)continue;const e=n.indexOf("="),r=decodeSafe(e>=0?n.slice(0,e):n);r&&(t[r]=e>=0?decodeSafe(n.slice(e+1)):"")}return t},trimSlashes=e=>e.replace(/^\/+/,"").replace(/\/+$/,"");export const parseDeepLink=e=>{if("string"!=typeof e)return null;const t=e.trim();if(!t||/\s/.test(t))return null;const n=t.split("#")[0]??"",r=n.indexOf("://");let i="",s=n;if(r>=0){const e=n.slice(0,r);if(!/^[a-zA-Z][a-zA-Z0-9+.-]*$/.test(e))return null;i=e.toLowerCase(),s=n.slice(r+3)}const o=s.indexOf("?"),c=o>=0?s.slice(0,o):s,a=parseQuery(o>=0?s.slice(o+1):"");let l="",u=c;if("http"===i||"https"===i){const e=c.indexOf("/");l=e>=0?c.slice(0,e):c,u=e>=0?c.slice(e+1):""}const d=trimSlashes(u),f=d?d.split("/").filter(Boolean):[];return i&&"http"!==i&&"https"!==i&&(l=f[0]??""),{url:t,scheme:i,host:l,path:d,segments:f,query:a}};const matchPattern=(e,t)=>{const n=trimSlashes(e).split("/").filter(Boolean);if(n.length!==t.length)return null;const r={};for(let e=0;e<n.length;e+=1){const i=n[e],s=t[e];if(i.startsWith(":")){const e=i.slice(1);if(!e)return null;r[e]=s}else if(i.toLowerCase()!==s.toLowerCase())return null}return r},matchRegExp=(e,t)=>{(e.global||e.sticky)&&(e.lastIndex=0);const n=e.exec(t);if(!n)return null;const r={};for(let e=1;e<n.length;e+=1){const t=n[e];void 0!==t&&(r[String(e)]=t)}for(const[e,t]of Object.entries(n.groups??{}))void 0!==t&&(r[e]=t);return r},matchRoute=(e,t)=>{for(const n of e){const e="string"==typeof n.match?matchPattern(n.match,t.segments):matchRegExp(n.match,t.path);if(e)return{route:n,params:e}}return null};let config=null,subscription=null,started=!1,pending=null,readyOverride=null;const isReady=()=>null!==readyOverride?readyOverride:config?.isReady?.()??!0,isAuthenticated=()=>config?.isAuthenticated?.()??!0,dispatch=e=>{const t=config;if(!t)return;const n=matchRoute(t.routes,e);if(n)return n.route.requiresAuth&&!isAuthenticated()?(pending=e,void t.onUnauthenticated?.(e)):void n.route.handler(e,n.params);t.onUnmatched?.(e)},flushPending=()=>{const e=pending;e&&(pending=null,dispatch(e))},configure=e=>{if(!e||!Array.isArray(e.routes))throw new Error(`${PREFIX} DeepLink.configure() needs a config object with a "routes" array. Pass { routes: [{ match: "order/:id", handler }] }.`);config=e},handleUrl=e=>{if(!config)return void Logger.error(`${PREFIX} DeepLink received a URL before configure() was called; the link was dropped. Call DeepLink.configure({ routes }) (or useDeepLink) during app start.`);const t=parseDeepLink(e);if(!t)return void config.onUnmatched?.({url:"string"==typeof e?e:"",scheme:"",host:"",path:"",segments:[],query:{}});const n=t;isReady()?dispatch(n):pending=n},start=async()=>{if(!config)throw new Error(`${PREFIX} DeepLink.start() was called before configure(). Call DeepLink.configure({ routes }) first, or use the useDeepLink() hook.`);if(!started){started=!0,subscription=Linking.addEventListener("url",e=>{handleUrl(e.url)});try{const e=await Linking.getInitialURL();e&&handleUrl(e)}catch(e){Logger.error(`${PREFIX} DeepLink could not read the cold-start URL`,e)}}},stop=()=>{subscription?.remove?.(),subscription=null,started=!1,pending=null,readyOverride=null},setReady=e=>{readyOverride=e,e&&flushPending()};export const DeepLink={configure:configure,start:start,stop:stop,handleUrl:handleUrl,setReady:setReady,replayPending:flushPending,getPending:()=>pending};export const useDeepLink=e=>{const t=useRef(e);t.current=e,useEffect(()=>(DeepLink.configure({get routes(){return t.current.routes},isReady:()=>t.current.isReady?.()??!0,isAuthenticated:()=>t.current.isAuthenticated?.()??!0,onUnauthenticated:e=>t.current.onUnauthenticated?.(e),onUnmatched:e=>t.current.onUnmatched?.(e)}),DeepLink.start(),()=>{DeepLink.stop()}),[])};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
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:
|
|
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);return i.create({intermediates:!0,overwrite:!0}),i.write(t),Promise.resolve()},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
|
-
export const asNumber=e=>{const r="number"==typeof e?e:Number(e);return Number.isFinite(r)?r:0};
|
|
1
|
+
"use strict";export const asNumber=e=>{const r="number"==typeof e?e:Number(e);return Number.isFinite(r)?r:0};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as
|
|
1
|
+
"use strict";import*as ExpoFileSystem from"expo-file-system";import{Platform}from"react-native";import{Logger}from"../logger/index.js";import{Permissions}from"../permissions/index.js";import{adaptExpoFileSystem}from"./adapters/expoFs.js";import{asNumber}from"./adapters/shared.js";const PREFIX="[@webority/mobile-core]",SCOPED_STORAGE_API_LEVEL=29,DOWNLOAD_TIMEOUT_MS=3e5;export class DownloadError extends Error{constructor(e,r,o){super(`${PREFIX} ${r}`),this.name="DownloadError",this.code=e,this.status=o,Object.setPrototypeOf(this,DownloadError.prototype)}}const describe=e=>e instanceof Error?e.message:String(e);let expoBackend,backend=null;const resolveBackend=()=>backend||(void 0===expoBackend&&(expoBackend=adaptExpoFileSystem(ExpoFileSystem)),expoBackend);export const setFileSystemImplementation=e=>{backend=e};const requireBackend=()=>{const e=resolveBackend();if(!e)throw new DownloadError("unsupported","No filesystem module is available, so files cannot be downloaded. expo-file-system did not load, which on a real build means the native module was not linked.");return e},stripControlChars=e=>Array.from(e).filter(e=>(e.codePointAt(0)??0)>31).join(""),lastSegment=e=>{const r=e.split(/[/\\]/);return stripControlChars(r[r.length-1]??"").trim()},sanitiseFileName=e=>{const r=lastSegment(e);if(""===r||"."===r||".."===r)throw new DownloadError("write-failed",`"${e}" does not contain a usable file name. Pass an explicit fileName.`);return r},fileNameFromUrl=e=>{const r=(e.split("#")[0]?.split("?")[0]??"").split("/").pop()??"";let o=r;try{o=decodeURIComponent(r)}catch{}const t=lastSegment(o);return""===t||"."===t||".."===t?"download":t},androidApiLevel=()=>"number"==typeof Platform.Version?Platform.Version:Number.parseInt(String(Platform.Version),10),ensureStoragePermission=async e=>{if("android"!==Platform.OS||"downloads"!==e)return;if(androidApiLevel()>=29)return;const r=await Permissions.ensure("storage");if("granted"!==r&&"limited"!==r)throw new DownloadError("permission-denied",`Storage permission is "${r}", so nothing can be written to the Downloads folder on this Android version. Ask the user to grant it (Permissions.openSettings()), or download to the "documents" destination instead.`)},emptyFile=e=>new DownloadError("empty-file",`The download of ${e} produced an empty file, so nothing was saved. Check that the URL is correct and that the request carried the credentials the server expects.`),requestFailed=(e,r,o)=>{if(r.signal?.aborted)return new DownloadError("aborted",`The download of ${o} was aborted.`);const t=e??{};if("RequestOfflineError"===t.name)return new DownloadError("network",`The device is offline, so ${r.url} was not downloaded.`);const a=t.response?.status;return"number"==typeof a?new DownloadError("http-error",`The server answered ${a} for ${r.url}, so no file was saved.`,a):new DownloadError("network",`The download of ${r.url} failed: ${describe(e)}`)},discardPartial=async(e,r)=>{try{await e.exists(r)&&await e.unlink(r)}catch(e){Logger.warn(`${PREFIX} Failed to remove the partial download at ${r}`,e)}};export const downloadFile=async e=>{const r=requireBackend(),o=e.destination??"documents",t=e.fileName?sanitiseFileName(e.fileName):fileNameFromUrl(e.url);await ensureStoragePermission(o);const a=r.dirs[o],n=`${a}/${t}`;if(e.signal?.aborted)throw new DownloadError("aborted",`The download of ${t} was aborted before it started.`);let i=!1;try{await r.mkdir(a);const o=await r.exists(n);o&&!1===e.overwrite?i=!0:o&&await r.unlink(n)}catch(e){throw new DownloadError("write-failed",`Could not prepare ${n} for writing: ${describe(e)}`)}if(i){const o=await r.stat(n);return{path:n,bytes:asNumber(o?.size),mimeType:e.mimeType,fromCache:!0}}const{onProgress:s}=e;let d;try{({data:d}=await e.client.get(e.url,{headers:{Accept:"*/*",...e.headers},responseType:"arraybuffer",timeout:3e5,signal:e.signal,onDownloadProgress:s?({loaded:e,total:r=0})=>s(e,r,r>0?e/r:0):void 0}))}catch(r){throw requestFailed(r,e,t)}if(e.signal?.aborted)throw new DownloadError("aborted",`The download of ${t} was aborted.`);const l=new Uint8Array(d??new ArrayBuffer(0));if(0===l.byteLength)throw emptyFile(e.url);try{await r.write(n,l)}catch(e){throw await discardPartial(r,n),new DownloadError("write-failed",`Could not write ${n}: ${describe(e)}`)}let w=0;try{w=await r.exists(n)?asNumber((await r.stat(n)).size):0}catch(e){throw await discardPartial(r,n),new DownloadError("write-failed",`The download of ${t} finished but ${n} could not be read back: ${describe(e)}`)}if(w<=0)throw await discardPartial(r,n),emptyFile(e.url);return{path:n,bytes:w,mimeType:e.mimeType,fromCache:!1}};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";export const SERVER_FAILURE_MESSAGE="Something went wrong on our side. Please try again in a moment.";export const OFFLINE_MESSAGE="You appear to be offline. Check your connection and try again.";export const TIMEOUT_MESSAGE="That took too long to respond. Check your connection and try again.";export const UNEXPECTED_MESSAGE="Something went wrong. Please try again.";export const REQUEST_CANCELED_CODE="request_canceled";export const CONTRACT_ERROR_CODE="contract_error";export const TIMEOUT_CODE="timeout";export const NETWORK_CODE="network";const MAX_MESSAGE_LENGTH=300,requestFailedMessage=e=>`Request failed (${e})`,isDict=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),nonEmptyString=e=>"string"==typeof e&&e.trim().length>0?e:null,looksLikeDiagnostics=e=>e.length>300||/^\s*</.test(e)||e.includes("\n at ")||/\b(Exception|StackTrace):/.test(e)||/\b(System|Microsoft)\.[A-Za-z]+\.[A-Za-z]/.test(e),userSafe=e=>{const t=nonEmptyString(e);return null===t||looksLikeDiagnostics(t)?null:t};export const toFieldPath=e=>e.replace(/^\$\.?/,"").split(".").map(e=>e.charAt(0).toLowerCase()+e.slice(1)).join(".");const firstMessage=e=>{if(Array.isArray(e)){for(const t of e){const e=nonEmptyString(t);if(null!==e)return e}return null}return nonEmptyString(e)},addError=(e,t,r)=>{const n=toFieldPath(t);""===n?e.form??=r:n in e.fields||(e.fields[n]=r)},readErrors=e=>{const t={fields:{},form:null};if(Array.isArray(e)){for(const r of e){if(!isDict(r))continue;const e=nonEmptyString(r.message);null!==e&&addError(t,"string"==typeof r.field?r.field:"",e)}return t}if(!isDict(e))return t;for(const[r,n]of Object.entries(e)){const e=firstMessage(n);null!==e&&addError(t,r,e)}return t},readLegacyError=e=>{const t=e.error;return isDict(t)?nonEmptyString(t.message):nonEmptyString(t)};export const isApiError=e=>isDict(e)&&"string"==typeof e.message&&"number"==typeof e.status&&"boolean"==typeof e.offline&&isDict(e.fieldErrors);const build=e=>({code:null,fieldErrors:{},status:0,offline:!1,traceId:null,detail:null,...e}),fromNoResponse=e=>{const t=nonEmptyString(e.code),r=nonEmptyString(e.name),n=nonEmptyString(e.message);return build("CanceledError"===r||"ERR_CANCELED"===t?{code:"request_canceled",message:UNEXPECTED_MESSAGE,detail:n}:"ECONNABORTED"===t||"ETIMEDOUT"===t?{code:"timeout",message:TIMEOUT_MESSAGE,offline:!0,detail:n}:"RequestOfflineError"===r||"ERR_NETWORK"===t||"Network Error"===n?{code:"network",message:OFFLINE_MESSAGE,offline:!0,detail:n}:{message:UNEXPECTED_MESSAGE,detail:n})};export function extractApiError(e){if(isApiError(e))return e;if("string"==typeof e)return build({message:userSafe(e)??UNEXPECTED_MESSAGE,detail:e||null});if(!isDict(e))return build({message:UNEXPECTED_MESSAGE,detail:null==e?null:String(e)});if(!0===e.isContractError)return build({code:"contract_error",message:userSafe(e.message)??UNEXPECTED_MESSAGE,detail:nonEmptyString(e.message)});const t=isDict(e.response)?e.response:null,r="number"==typeof t?.status?t.status:"number"==typeof e.status?e.status:0,n=t?t.data:e.body;if(0===r&&null==n)return fromNoResponse(e);const s=isDict(n)?n:null,{fields:o,form:i}=readErrors(s?.errors),a=nonEmptyString(s?.code),E=nonEmptyString(s?.traceId),l=nonEmptyString(s?.message)??nonEmptyString(s?.detail)??(s?readLegacyError(s):null)??nonEmptyString(s?.title)??nonEmptyString(n)??nonEmptyString(e.message);let c;return c=r>=500?SERVER_FAILURE_MESSAGE:userSafe(Object.values(o)[0])??userSafe(i)??userSafe(s?.message)??userSafe(s?.detail)??(s?userSafe(readLegacyError(s)):null)??userSafe(s?.title)??userSafe(n)??(r?requestFailedMessage(r):UNEXPECTED_MESSAGE),build({code:a,message:c,fieldErrors:o,status:r,traceId:E,detail:l})}export const isNoResponse=e=>extractApiError(e).offline;export function apiErrorMessage(e,t){const r=extractApiError(e);if(r.offline||null!==t&&!t)return r.message;return r.status>=500||"request_canceled"===r.code||r.message===UNEXPECTED_MESSAGE||r.message===requestFailedMessage(r.status)?t??null:r.message}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";export{apiErrorMessage,CONTRACT_ERROR_CODE,extractApiError,isApiError,isNoResponse,NETWORK_CODE,OFFLINE_MESSAGE,REQUEST_CANCELED_CODE,SERVER_FAILURE_MESSAGE,TIMEOUT_CODE,TIMEOUT_MESSAGE,toFieldPath,UNEXPECTED_MESSAGE}from"./extractApiError.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
"use strict";import{configuredLocale,getFormatterConfig,isFormatterConfigured}from"./formatConfig.js";import{numberFormat}from"./intlCache.js";const hasIntlNumber=()=>"undefined"!=typeof Intl&&"function"==typeof Intl.NumberFormat,indianGroupingFallback=(r,t)=>{const e=r<0?"-":"",n=Math.abs(r).toFixed(t),[i,o]=n.split("."),m=i.length>3?i.slice(-3):i,u=i.length>3?i.slice(0,-3):"";return e+(u?u.replace(/\B(?=(\d{2})+(?!\d))/g,",")+","+m:m)+(o?`.${o}`:"")},toAmount=r=>{if(null==r||"string"==typeof r&&""===r.trim())return null;const t="number"==typeof r?r:Number(r);return Number.isFinite(t)?t:null},currencyDigits=(r,t)=>numberFormat(r,{style:"currency",currency:t}).resolvedOptions().maximumFractionDigits??2;export const formatCurrency=(r,t={})=>{const{currency:e="INR",locale:n=configuredLocale()??"en-IN",minimumFractionDigits:i,maximumFractionDigits:o,stripSymbol:m=!1,empty:u=(isFormatterConfigured("locale")||isFormatterConfigured("empty")?getFormatterConfig().empty:""),...c}=t,a=toAmount(r);if(null===a)return u;if(hasIntlNumber())try{const r=o??currencyDigits(n,e),t=i??(Number.isInteger(a)?0:r),u=numberFormat(n,{...c,style:"currency",currency:e,minimumFractionDigits:t,maximumFractionDigits:Math.max(t,r)}).format(a);return m?u.replace(/[^\d,.\s\-+]/g,"").trim():u}catch{}const s=indianGroupingFallback(a,i??(Number.isInteger(a)?0:2));return m?s:"INR"===e?`₹${s}`:`${e} ${s}`};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
"use strict";import{formatDate as houseDate,formatDateTime as houseDateTime,formatTime as houseTime}from"./house.js";import{dateTimeFormat,relativeTimeFormat}from"./intlCache.js";const toDate=t=>{if(t instanceof Date)return Number.isNaN(t.getTime())?null:t;const e=new Date(t);return Number.isNaN(e.getTime())?null:e},hasIntl=()=>"undefined"!=typeof Intl&&"function"==typeof Intl.DateTimeFormat,PAD=t=>t<10?`0${t}`:`${t}`,fallbackDate=(t,e)=>{const a=PAD(t.getDate()),r=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][t.getMonth()],n=["January","February","March","April","May","June","July","August","September","October","November","December"][t.getMonth()],o=t.getFullYear(),i=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][t.getDay()];switch(e){case"short":return`${a}/${PAD(t.getMonth()+1)}/${o}`;case"long":return`${a} ${n} ${o}`;case"full":return`${i}, ${a} ${n} ${o}`;default:return`${a} ${r} ${o}`}},fallbackTime=(t,e)=>{const a=PAD(t.getHours()),r=PAD(t.getMinutes());if("short"===e)return`${a}:${r}`;return`${a}:${r}:${PAD(t.getSeconds())}`},isStyle=t=>"string"==typeof t;export function formatDate(t,e,a="en-IN"){if(!isStyle(e))return houseDate(t,e);const r=e,n=toDate(t);if(!n)return"";if(hasIntl())try{return dateTimeFormat(a,{dateStyle:r}).format(n)}catch{}return fallbackDate(n,r)}export function formatTime(t,e,a="en-IN"){if(!isStyle(e))return houseTime(t,e);const r=e,n=toDate(t);if(!n)return"";if(hasIntl())try{return dateTimeFormat(a,{timeStyle:r}).format(n)}catch{}return fallbackTime(n,r)}export function formatDateTime(t,e,a="short",r="en-IN"){if(!isStyle(e))return houseDateTime(t,e);const n=e,o=toDate(t);if(!o)return"";if(hasIntl())try{return dateTimeFormat(r,{dateStyle:n,timeStyle:a}).format(o)}catch{}return`${fallbackDate(o,n)}, ${fallbackTime(o,a)}`}const SECOND=1e3,MINUTE=6e4,HOUR=36e5,DAY=24*HOUR,WEEK=7*DAY,MONTH=30*DAY,YEAR=365*DAY;export const formatRelativeTime=(t,e=new Date,a="en-IN")=>{const r=toDate(t),n=toDate(e);if(!r||!n)return"";const o=r.getTime()-n.getTime(),i=Math.abs(o);let u,s;i<6e4?(u="second",s=Math.round(o/1e3)):i<HOUR?(u="minute",s=Math.round(o/6e4)):i<DAY?(u="hour",s=Math.round(o/HOUR)):i<WEEK?(u="day",s=Math.round(o/DAY)):i<MONTH?(u="week",s=Math.round(o/WEEK)):i<YEAR?(u="month",s=Math.round(o/MONTH)):(u="year",s=Math.round(o/YEAR));const m=hasIntl()?Intl.RelativeTimeFormat:void 0;if("function"==typeof m)try{return relativeTimeFormat(m,a).format(s,u)}catch{}const l=s<0,c=Math.abs(s),f=1===c?u:`${u}s`;return l?`${c} ${f} ago`:`in ${c} ${f}`};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{dateTimeFormat
|
|
1
|
+
"use strict";import{dateTimeFormat}from"./intlCache.js";import{WINDOWS_TO_IANA}from"./windowsToIanaTable.js";const toDate=t=>{if(t instanceof Date)return Number.isNaN(t.getTime())?null:t;const e=new Date(t);return Number.isNaN(e.getTime())?null:e},PAD=t=>t<10?`0${t}`:`${t}`;export const isSameDay=(t,e)=>{const r=toDate(t),n=toDate(e);return!(!r||!n)&&(r.getFullYear()===n.getFullYear()&&r.getMonth()===n.getMonth()&&r.getDate()===n.getDate())};export const isDateBefore=(t,e)=>{const r=toDate(t),n=toDate(e);return null!==r&&null!==n&&r.getTime()<n.getTime()};export const isDateAfter=(t,e)=>{const r=toDate(t),n=toDate(e);return null!==r&&null!==n&&r.getTime()>n.getTime()};export const diffMs=(t,e)=>{const r=toDate(t),n=toDate(e);return r&&n?r.getTime()-n.getTime():Number.NaN};export const startOfDay=t=>{const e=toDate(t);if(!e)return null;const r=new Date(e);return r.setHours(0,0,0,0),r};export const addDays=(t,e)=>{if(null==t||""===t||!Number.isFinite(e))return null;const r=toDate(t);if(!r)return null;const n=new Date(r);return n.setDate(n.getDate()+e),n};const WEEKDAY_SHORT=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],WEEKDAY_LONG=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],MONTH_LONG=["January","February","March","April","May","June","July","August","September","October","November","December"],TOKENS=["YYYY","YY","MMMM","MMM","MM","M","DD","D","dddd","ddd","HH","H","hh","h","mm","m","ss","s","A","a"],tokenizePattern=t=>{const e=[];let r=0;t:for(;r<t.length;){for(const n of TOKENS)if(t.startsWith(n,r)){e.push(n),r+=n.length;continue t}e.push(t[r]),r+=1}return e};export const formatDatePattern=(t,e,r)=>{const n=toDate(t);if(!n)return"";const o=r?.utc??!1,a=o?n.getUTCFullYear():n.getFullYear(),u=o?n.getUTCMonth():n.getMonth(),s=o?n.getUTCDate():n.getDate(),i=o?n.getUTCDay():n.getDay(),c=o?n.getUTCHours():n.getHours(),D=o?n.getUTCMinutes():n.getMinutes(),g=o?n.getUTCSeconds():n.getSeconds(),{hour12:m,period:l}=to12Hour(c);return tokenizePattern(e).map(t=>{switch(t){case"YYYY":return String(a);case"YY":return String(a).slice(-2);case"MMMM":return MONTH_LONG[u];case"MMM":return MONTH_SHORT[u];case"MM":return PAD(u+1);case"M":return String(u+1);case"DD":return PAD(s);case"D":return String(s);case"dddd":return WEEKDAY_LONG[i];case"ddd":return WEEKDAY_SHORT[i];case"HH":return PAD(c);case"H":return String(c);case"hh":return PAD(m);case"h":return String(m);case"mm":return PAD(D);case"m":return String(D);case"ss":return PAD(g);case"s":return String(g);case"A":return l;case"a":return l.toLowerCase();default:return t}}).join("")};const MONTH_SHORT=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];export const formatDateDDMMMYYYY=(t,e)=>{const r=toDate(t);return r?e?.utc?`${PAD(r.getUTCDate())} ${MONTH_SHORT[r.getUTCMonth()]}, ${r.getUTCFullYear()}`:`${PAD(r.getDate())} ${MONTH_SHORT[r.getMonth()]}, ${r.getFullYear()}`:""};export const formatDateISO=t=>{const e=toDate(t);return e?`${e.getFullYear()}-${PAD(e.getMonth()+1)}-${PAD(e.getDate())}`:""};const to12Hour=t=>({hour12:t%12||12,period:t>=12?"PM":"AM"});export const formatTime12h=t=>{const e=toDate(t);if(!e)return"";const{hour12:r,period:n}=to12Hour(e.getHours());return`${PAD(r)}:${PAD(e.getMinutes())} ${n}`};const hasIntl=()=>"undefined"!=typeof Intl&&"function"==typeof Intl.DateTimeFormat;export const formatTimeInZone=(t,e)=>{const r=toDate(t);if(!r)return"";if(!hasIntl())return formatTime12h(r);const n=dateTimeFormat("en-US",{timeZone:e,hour:"numeric",minute:"2-digit",hour12:!0}).formatToParts(r),get=t=>n.find(e=>e.type===t)?.value??"",o=Number.parseInt(get("hour"),10),a=get("minute"),u=get("dayPeriod").toLowerCase();return`${PAD(o)}:${a} ${u}`};export const formatTimeInWindowsZone=(t,e)=>{const r=WINDOWS_TO_IANA[e];if(!r)throw new Error(`Mapping for Windows time zone '${e}' not found.`);return formatTimeInZone(t,r)};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";const DEFAULTS={zone:"IST",locale:"en-IN",empty:"-"};let current={...DEFAULTS},configured=new Set;export const configureFormatters=e=>{if(void 0===e)return current={...DEFAULTS},void(configured=new Set);for(const o of Object.keys(e)){const r=e[o];void 0!==r&&(current={...current,[o]:r},configured.add(o))}};export const getFormatterConfig=()=>({...current});export const isFormatterConfigured=e=>configured.has(e);export const configuredLocale=()=>configured.has("locale")?current.locale:null;export const groupingForLocale=e=>/-IN(?:-|$)/i.test(e)?"indian":"international";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";import{configuredLocale,getFormatterConfig,groupingForLocale}from"./formatConfig.js";import{dateTimeFormat,numberFormat,relativeTimeFormat}from"./intlCache.js";const MONTHS=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],IST_OFFSET_MINUTES=330,IST_NAMES=["IST","Asia/Kolkata","Asia/Calcutta"],DATE_ONLY=/^\d{4}-\d{2}-\d{2}$/,pad2=t=>t<10?`0${t}`:`${t}`,emptyOf=t=>t??getFormatterConfig().empty,toInstant=t=>{if(null==t||""===t)return null;const e=t instanceof Date?t:new Date("string"==typeof t?t.trim():t);return Number.isNaN(e.getTime())?null:e},isDateOnly=t=>"string"==typeof t&&DATE_ONLY.test(t.trim()),gmtLabel=t=>{if(0===t)return"GMT";const e=t>0?"+":"-",n=Math.abs(t),o=n%60;return`GMT${e}${Math.floor(n/60)}${0===o?"":`:${pad2(o)}`}`},shifted=(t,e,n)=>{const o=new Date(t.getTime()+6e4*e);return{year:o.getUTCFullYear(),month:o.getUTCMonth(),day:o.getUTCDate(),hour:o.getUTCHours(),minute:o.getUTCMinutes(),label:n}},inIanaZone=(t,e)=>{const n=dateTimeFormat("en-US",{timeZone:e,year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",hour12:!1}).formatToParts(t),read=t=>Number.parseInt(n.find(e=>e.type===t)?.value??"",10),o=read("year"),r=read("month")-1,i=read("day"),a=read("hour")%24,l=read("minute"),m=Date.UTC(o,r,i,a,l),u=Math.round((m-6e4*Math.floor(t.getTime()/6e4))/6e4);return{year:o,month:r,day:i,hour:a,minute:l,label:gmtLabel(u)}},wallClock=(t,e)=>IST_NAMES.includes(e)?shifted(t,330,"IST"):"UTC"===e?shifted(t,0,"UTC"):"viewer"===e?{year:t.getFullYear(),month:t.getMonth(),day:t.getDate(),hour:t.getHours(),minute:t.getMinutes(),label:gmtLabel(-t.getTimezoneOffset())}:inIanaZone(t,e),hourCycleOf=t=>t.hourCycle??12,dayMonthYear=t=>`${pad2(t.day)}-${MONTHS[t.month]}-${t.year}`,clockTime=(t,e)=>24===e?`${pad2(t.hour)}:${pad2(t.minute)}`:`${t.hour%12||12}:${pad2(t.minute)} ${t.hour<12?"AM":"PM"}`,labelled=(t,e)=>e??!IST_NAMES.includes(t),withLabel=(t,e,n,o)=>labelled(n,o)?`${t} ${e.label}`:t,intlZone=t=>{if("viewer"!==t)return IST_NAMES.includes(t)?"Asia/Kolkata":t},localeDayMonthYear=(t,e,n)=>{const o=dateTimeFormat(e,{day:"2-digit",month:"short",year:"numeric",timeZone:n}).formatToParts(t),part=t=>o.find(e=>e.type===t)?.value??"";return`${part("day")}-${part("month").replace(".","")}-${part("year")}`},localeClock=(t,e,n,o)=>dateTimeFormat(e,{hour:"2-digit",minute:"2-digit",timeZone:intlZone(n),timeZoneName:labelled(n,o.zoneLabel)?"short":void 0,hourCycle:void 0===o.hourCycle?void 0:24===o.hourCycle?"h23":"h12"}).format(t);export const formatDate=(t,e={})=>{const n=toInstant(t);if(!n)return emptyOf(e.empty);const o=isDateOnly(t)?"UTC":e.zone??getFormatterConfig().zone,r=configuredLocale();return r?localeDayMonthYear(n,r,intlZone(o)):dayMonthYear(wallClock(n,o))};export const formatTime=(t,e={})=>{const n=toInstant(t);if(!n)return emptyOf(e.empty);const o=e.zone??getFormatterConfig().zone,r=configuredLocale();if(r)return localeClock(n,r,o,e);const i=wallClock(n,o);return withLabel(clockTime(i,hourCycleOf(e)),i,o,e.zoneLabel)};export const formatDateTime=(t,e={})=>{const n=toInstant(t);if(!n)return emptyOf(e.empty);const o=e.zone??getFormatterConfig().zone,r=configuredLocale();if(r)return`${localeDayMonthYear(n,r,intlZone(o))}, ${localeClock(n,r,o,e)}`;const i=wallClock(n,o);return withLabel(`${dayMonthYear(i)}, ${clockTime(i,hourCycleOf(e))}`,i,o,e.zoneLabel)};const SECOND=1e3,MINUTE=6e4,HOUR=36e5,DAY=24*HOUR,WEEK=7*DAY,MONTH=30*DAY,YEAR=365*DAY,INTL_UNITS=[["year",YEAR],["month",MONTH],["day",DAY],["hour",HOUR],["minute",6e4]];export const formatRelative=(t,e={})=>{const n=toInstant(t),o=toInstant(e.now??Date.now());if(!n||!o)return emptyOf(e.empty);const r=n.getTime()-o.getTime(),i=Math.abs(r),a=Intl.RelativeTimeFormat,l=configuredLocale();if((null!==l||!0===e.intl)&&"function"==typeof a){const t=relativeTimeFormat(a,l??getFormatterConfig().locale),[e,n]=INTL_UNITS.find(([,t])=>i>=t)??["second",1e3];return t.format(Math.round(r/n),e)}if(i<6e4)return"just now";const[m,u]=i<HOUR?["minute",6e4]:i<DAY?["hour",HOUR]:i<WEEK?["day",DAY]:i<MONTH?["week",WEEK]:i<YEAR?["month",MONTH]:["year",YEAR],c=Math.floor(i/u),s=`${c} ${m}${1===c?"":"s"}`;return r<0?`${s} ago`:`in ${s}`};const toNumber=t=>{if(null==t)return null;if("string"==typeof t&&""===t.trim())return null;const e="number"==typeof t?t:Number(t);return Number.isFinite(e)?e:null},clampDigits=t=>Math.min(20,Math.max(0,Math.trunc(t))),shiftDecimal=(t,e)=>/e/i.test(String(t))?t*10**e:Number(`${t}e${e}`),groupInteger=(t,e)=>{if("none"===e||t.length<=3)return t;if("international"===e)return t.replace(/\B(?=(\d{3})+(?!\d))/g,",");return`${t.slice(0,-3).replace(/\B(?=(\d{2})+(?!\d))/g,",")},${t.slice(-3)}`},hasIntlNumber=()=>"undefined"!=typeof Intl&&"function"==typeof Intl.NumberFormat,plainDigits=(t,e)=>{if(hasIntlNumber())return numberFormat("en-US",{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:e}).format(t);const n=Math.min(e,15);return shiftDecimal(Math.round(shiftDecimal(t,n)),-n).toFixed(n)},decimalText=(t,e,n,o)=>{const r=Math.max(clampDigits(n),clampDigits(e)),i=clampDigits(e),a=plainDigits(Math.abs(t),r),[l="0",m=""]=a.split(".");let u=m.padEnd(i,"0");for(;u.length>i&&u.endsWith("0");)u=u.slice(0,-1);const c=groupInteger(l,o)+(u?`.${u}`:"");return t<0&&/[1-9]/.test(a)?`-${c}`:c},HOUSE_NUMBER_KEYS=new Set(["grouping","minimumFractionDigits","maximumFractionDigits","locale","empty","scale"]),intlNumberOptions=t=>{if(!Object.entries(t).some(([t,e])=>void 0!==e&&!HOUSE_NUMBER_KEYS.has(t)))return null;const{grouping:e,locale:n,empty:o,scale:r,...i}=t;return"none"===e&&void 0===i.useGrouping?{...i,useGrouping:!1}:i},localeOf=t=>t.locale??getFormatterConfig().locale,intlTextLocale=t=>{const e=configuredLocale();return null===e||"indian"===t.grouping||"international"===t.grouping?null:t.locale??e},fractionDigits=(t,e)=>{const n=clampDigits(t);return{minimumFractionDigits:n,maximumFractionDigits:Math.max(n,clampDigits(e))}},groupingOption=t=>"none"===t?{useGrouping:!1}:{};export const formatNumber=(t,e={})=>{const n=toNumber(t);if(null===n)return emptyOf(e.empty);const o=intlNumberOptions(e);if(o)return numberFormat(localeOf(e),o).format(n);const r=intlTextLocale(e);return r?numberFormat(r,{...fractionDigits(e.minimumFractionDigits??0,e.maximumFractionDigits??3),...groupingOption(e.grouping)}).format(n):decimalText(n,e.minimumFractionDigits??0,e.maximumFractionDigits??3,e.grouping??groupingForLocale(localeOf(e)))};export const formatPercent=(t,e={})=>{const n=toNumber(t);if(null===n)return emptyOf(e.empty);const o=intlNumberOptions(e);if(o){const t="percent"===e.scale?shiftDecimal(n,-2):n;return numberFormat(localeOf(e),{style:"percent",...o}).format(t)}const r=intlTextLocale(e);if(r){const t="percent"===e.scale?shiftDecimal(n,-2):n;return numberFormat(r,{style:"percent",...fractionDigits(e.minimumFractionDigits??0,e.maximumFractionDigits??e.minimumFractionDigits??0),...groupingOption(e.grouping)}).format(t)}const i="percent"===e.scale?n:shiftDecimal(n,2);return`${decimalText(i,e.minimumFractionDigits??0,e.maximumFractionDigits??e.minimumFractionDigits??0,e.grouping??groupingForLocale(localeOf(e)))}%`};const SYMBOLS={INR:"₹",USD:"$",EUR:"€",GBP:"£"},MINOR_DIGITS={JPY:0,KRW:0,VND:0,BHD:3,JOD:3,KWD:3,OMR:3,TND:3};export const formatMinor=(t,e={})=>{const n=toNumber(t);if(null===n)return emptyOf(e.empty);const o=(e.currency??"INR").toUpperCase(),r=MINOR_DIGITS[o]??2,i=Math.round(Math.abs(n)),a=String(i).padStart(r+1,"0"),l=a.slice(0,a.length-r);let m=a.slice(a.length-r);e.dropZeroDecimals&&/^0*$/.test(m)&&(m="");const u=intlTextLocale({grouping:e.grouping});if(u)try{const t=Number(`${n<0&&0!==i?"-":""}${l}.${a.slice(a.length-r)||"0"}`);return numberFormat(u,{...!1===e.symbol?{}:{style:"currency",currency:o},...fractionDigits(m?r:0,r),...groupingOption(e.grouping)}).format(t)}catch{}const c=e.grouping??("INR"===o?"indian":"international"),s=groupInteger(l,c)+(m?`.${m}`:""),g=n<0&&0!==i?"-":"";if(!1===e.symbol)return`${g}${s}`;const f=SYMBOLS[o];return f?`${g}${f}${s}`:`${g}${o} ${s}`};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{formatCurrency}from"./currency.js";export{formatDate,formatDateTime,formatRelativeTime,formatTime}from"./date.js";export{addDays,diffMs,formatDateDDMMMYYYY,formatDateISO,formatDatePattern,formatTime12h,formatTimeInWindowsZone,formatTimeInZone,isDateAfter,isDateBefore,isSameDay,startOfDay}from"./dateMath.js";export{getInitials}from"./initials.js";export{formatCompactNumber,formatNumber,formatPercent}from"./number.js";export{AsYouType,clampNationalNumber,countryFlagEmoji,detectPhoneCountry,formatPhone,formatPhoneAsTyped,getCountries,getCountryCallingCode,getPhoneCountries,isSupportedCountry,isValidNationalNumber,isValidPhoneNumber,maxNationalNumberLength,normalizePhone,parsePhoneNumber,parsePhoneNumberFromString,splitPhoneNumber,validatePhoneNumberLength}from"./phone.js";
|
|
1
|
+
"use strict";export{formatCurrency}from"./currency.js";export{formatDate,formatDateTime,formatRelativeTime,formatTime}from"./date.js";export{addDays,diffMs,formatDateDDMMMYYYY,formatDateISO,formatDatePattern,formatTime12h,formatTimeInWindowsZone,formatTimeInZone,isDateAfter,isDateBefore,isSameDay,startOfDay}from"./dateMath.js";export{configureFormatters,getFormatterConfig}from"./formatConfig.js";export{formatMinor,formatRelative}from"./house.js";export{getInitials}from"./initials.js";export{formatCompactNumber,formatNumber,formatPercent}from"./number.js";export{AsYouType,clampNationalNumber,countryFlagEmoji,detectPhoneCountry,formatPhone,formatPhoneAsTyped,getCountries,getCountryCallingCode,getPhoneCountries,isSupportedCountry,isValidNationalNumber,isValidPhoneNumber,maxNationalNumberLength,normalizePhone,parsePhoneNumber,parsePhoneNumberFromString,splitPhoneNumber,validatePhoneNumberLength}from"./phone.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export const getInitials=(t,e=2)=>{if(!t)return"";const r=t.trim();if(!r)return"";const
|
|
1
|
+
"use strict";export const getInitials=(t,e=2)=>{if(!t)return"";const r=t.trim();if(!r)return"";const s=r.split(/\s+/);if(1===s.length){return(s[0]??"").slice(0,e).toUpperCase()}return s.slice(0,e).map(t=>(t[0]??"").toUpperCase()).join("")};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const cached=(e,t,
|
|
1
|
+
"use strict";const LIMIT=100,cached=(e,t,r)=>{let a=e.get(t);return void 0===a&&(a=r(),e.size>=100&&e.clear(),e.set(t,a)),a},numberFormats=new Map,dateTimeFormats=new Map,relativeTimeFormats=new Map;export const numberFormat=(e,t={})=>cached(numberFormats,`${e}|${JSON.stringify(t)}`,()=>new Intl.NumberFormat(e,t));export const dateTimeFormat=(e,t)=>cached(dateTimeFormats,`${e}|${JSON.stringify(t)}`,()=>new Intl.DateTimeFormat(e,t));export const relativeTimeFormat=(e,t)=>cached(relativeTimeFormats,t,()=>new e(t,{numeric:"auto"}));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
"use strict";import{formatNumber as houseNumber,formatPercent as housePercent}from"./house.js";import{numberFormat}from"./intlCache.js";const hasIntlNumber=()=>"undefined"!=typeof Intl&&"function"==typeof Intl.NumberFormat;export function formatNumber(t,r,e){if("number"!=typeof r&&void 0===e)return houseNumber(t,r);const n="number"==typeof r?r:void 0,o=t;if(null==o||Number.isNaN(o))return"";if(hasIntlNumber())try{const t={};return null!=n&&(t.minimumFractionDigits=n,t.maximumFractionDigits=n),numberFormat(e??"en-IN",t).format(o)}catch{}return null!=n?o.toFixed(n):String(o)}export function formatPercent(t,r,e,n){if("number"!=typeof r&&void 0===e&&void 0===n)return housePercent(t,r);const o="number"==typeof r?r:0,m=t;if(null==m||Number.isNaN(m))return"";const i=e??1?m:m/100;if(hasIntlNumber())try{return numberFormat(n??"en-IN",{style:"percent",minimumFractionDigits:o,maximumFractionDigits:o}).format(i)}catch{}return`${(100*i).toFixed(o)}%`}export const formatCompactNumber=(t,r="en-IN")=>{if(null==t||Number.isNaN(t))return"";if(hasIntlNumber())try{return numberFormat(r,{notation:"compact",maximumFractionDigits:1}).format(t)}catch{}const e=Math.abs(t),n=t<0?"-":"";return e>=1e7?`${n}${(e/1e7).toFixed(1)}Cr`:e>=1e5?`${n}${(e/1e5).toFixed(1)}L`:e>=1e3?`${n}${(e/1e3).toFixed(1)}K`:`${t}`};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Metadata
|
|
1
|
+
"use strict";import{Metadata}from"libphonenumber-js/core";import{AsYouType,getCountries,getCountryCallingCode,parsePhoneNumberFromString,validatePhoneNumberLength}from"libphonenumber-js/max";import phoneMetadata from"libphonenumber-js/metadata.max.json";export{AsYouType,getCountries,getCountryCallingCode,isSupportedCountry,isValidPhoneNumber,parsePhoneNumber,parsePhoneNumberFromString,validatePhoneNumberLength}from"libphonenumber-js/max";export const normalizePhone=t=>{if(!t)return"";const e=t.trim(),n=e.startsWith("+"),r=e.replace(/\D/g,"");return n?`+${r}`:r};export const detectPhoneCountry=(t,e="+91")=>{const n=normalizePhone(t);if(!n)return null;if(n.startsWith("+"))return parsePhoneNumberFromString(n)?.country??null;const r=normalizePhone(e);return r.startsWith("+")?parsePhoneNumberFromString(r+n)?.country??null:null};const bestEffortGroup=t=>{const e=t.length>11?3:t.length>10?2:1;return`+${t.slice(0,e)} ${t.slice(e).replace(/(.{4})(?=.)/g,"$1 ").trim()}`.trim()};export function formatPhone(t,e){if(!t)return"";const n=normalizePhone(t);if(!n)return"";const r="string"==typeof e?{}:e??{},o="string"==typeof e?e:r.defaultCountryCode??"+91",i=n.startsWith("+");let s,a=n;if(r.country)s=parsePhoneNumberFromString(n,r.country);else if(i)s=parsePhoneNumberFromString(n);else{const t=normalizePhone(o);if(t.startsWith("+")){const e=t+n;s=parsePhoneNumberFromString(e),a=e}else s=void 0}const u=i||!r.country;if(s?.isValid()){return r.includeCountryCode??u?s.formatInternational():s.formatNational()}return a.startsWith("+")?bestEffortGroup(a.slice(1)):a.replace(/(.{4})(?=.)/g,"$1 ").trim()}const onlyDigits=t=>t.replace(/\D/g,"");export const splitPhoneNumber=(t,e)=>{const n=normalizePhone(t);if(!n||0===onlyDigits(n).length)return null;const r=n.startsWith("+")?parsePhoneNumberFromString(n):e?parsePhoneNumberFromString(n,e):void 0;return r?{country:r.country??null,callingCode:r.countryCallingCode,nationalNumber:r.nationalNumber}:null};export const clampNationalNumber=(t,e)=>{let n=onlyDigits(t);for(;n.length>0&&"TOO_LONG"===validatePhoneNumberLength(n,e);)n=n.slice(0,-1);return n};const SUBSCRIBER_TYPES={any:["MOBILE","FIXED_LINE"],mobile:["MOBILE"]};export const maxNationalNumberLength=(t,e="any")=>{const n=new Metadata(phoneMetadata);n.selectNumberingPlan(t);const r=n.numberingPlan;if(!r)return E164_MAX_NATIONAL_DIGITS;const o=SUBSCRIBER_TYPES[e].flatMap(t=>r.type(t)?.possibleLengths()??[]);return Math.max(...o.length>0?o:r.possibleLengths())};const E164_MAX_NATIONAL_DIGITS=15;export const formatPhoneAsTyped=(t,e)=>{const n=clampNationalNumber(t,e);if(!n)return"";const r=new AsYouType(e).input(n);if(r!==n)return r;const o=`+${getCountryCallingCode(e)}`,i=(new AsYouType).input(`${o}${n}`);return i.startsWith(o)&&i.slice(o.length).trimStart()||n};export const isValidNationalNumber=(t,e,n="any")=>{const r=onlyDigits(t);if(!r)return!1;const o=parsePhoneNumberFromString(r,e);if(!o?.isValid())return!1;if("any"===n)return!0;const i=o.getType();return void 0===i||"MOBILE"===i||"FIXED_LINE_OR_MOBILE"===i};export const countryFlagEmoji=t=>{const e=t.trim().toUpperCase();return/^[A-Z]{2}$/.test(e)?String.fromCodePoint(127462+e.charCodeAt(0)-65,127462+e.charCodeAt(1)-65):""};export const getPhoneCountries=()=>getCountries().map(t=>({iso:t,callingCode:getCountryCallingCode(t)}));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export const WINDOWS_TO_IANA={"AUS Central Standard Time":"Australia/Darwin","AUS Eastern Standard Time":"Australia/Sydney","Afghanistan Standard Time":"Asia/Kabul","Alaskan Standard Time":"America/Anchorage","Aleutian Standard Time":"America/Adak","Altai Standard Time":"Asia/Barnaul","Arab Standard Time":"Asia/Riyadh","Arabian Standard Time":"Asia/Dubai","Arabic Standard Time":"Asia/Baghdad","Argentina Standard Time":"America/Buenos_Aires","Astrakhan Standard Time":"Europe/Astrakhan","Atlantic Standard Time":"America/Halifax","Aus Central W. Standard Time":"Australia/Eucla","Azerbaijan Standard Time":"Asia/Baku","Azores Standard Time":"Atlantic/Azores","Bahia Standard Time":"America/Bahia","Bangladesh Standard Time":"Asia/Dhaka","Belarus Standard Time":"Europe/Minsk","Bougainville Standard Time":"Pacific/Bougainville","Canada Central Standard Time":"America/Regina","Cape Verde Standard Time":"Atlantic/Cape_Verde","Caucasus Standard Time":"Asia/Yerevan","Cen. Australia Standard Time":"Australia/Adelaide","Central America Standard Time":"America/Guatemala","Central Asia Standard Time":"Asia/Almaty","Central Brazilian Standard Time":"America/Cuiaba","Central Europe Standard Time":"Europe/Budapest","Central European Standard Time":"Europe/Warsaw","Central Pacific Standard Time":"Pacific/Guadalcanal","Central Standard Time":"America/Chicago","Central Standard Time (Mexico)":"America/Mexico_City","Chatham Islands Standard Time":"Pacific/Chatham","China Standard Time":"Asia/Shanghai","Cuba Standard Time":"America/Havana","Dateline Standard Time":"Etc/GMT+12","E. Africa Standard Time":"Africa/Nairobi","E. Australia Standard Time":"Australia/Brisbane","E. Europe Standard Time":"Europe/Chisinau","E. South America Standard Time":"America/Sao_Paulo","Easter Island Standard Time":"Pacific/Easter","Eastern Standard Time":"America/New_York","Eastern Standard Time (Mexico)":"America/Cancun","Egypt Standard Time":"Africa/Cairo","Ekaterinburg Standard Time":"Asia/Yekaterinburg","FLE Standard Time":"Europe/Kiev","Fiji Standard Time":"Pacific/Fiji","GMT Standard Time":"Europe/London","GTB Standard Time":"Europe/Bucharest","Georgian Standard Time":"Asia/Tbilisi","Greenland Standard Time":"America/Godthab","Greenwich Standard Time":"Atlantic/Reykjavik","Haiti Standard Time":"America/Port-au-Prince","Hawaiian Standard Time":"Pacific/Honolulu","India Standard Time":"Asia/Calcutta","Iran Standard Time":"Asia/Tehran","Israel Standard Time":"Asia/Jerusalem","Jordan Standard Time":"Asia/Amman","Kaliningrad Standard Time":"Europe/Kaliningrad","Korea Standard Time":"Asia/Seoul","Libya Standard Time":"Africa/Tripoli","Line Islands Standard Time":"Pacific/Kiritimati","Lord Howe Standard Time":"Australia/Lord_Howe","Magadan Standard Time":"Asia/Magadan","Magallanes Standard Time":"America/Punta_Arenas","Marquesas Standard Time":"Pacific/Marquesas","Mauritius Standard Time":"Indian/Mauritius","Middle East Standard Time":"Asia/Beirut","Montevideo Standard Time":"America/Montevideo","Morocco Standard Time":"Africa/Casablanca","Mountain Standard Time":"America/Denver","Mountain Standard Time (Mexico)":"America/Chihuahua","Myanmar Standard Time":"Asia/Rangoon","N. Central Asia Standard Time":"Asia/Novosibirsk","Namibia Standard Time":"Africa/Windhoek","Nepal Standard Time":"Asia/Katmandu","New Zealand Standard Time":"Pacific/Auckland","Newfoundland Standard Time":"America/St_Johns","Norfolk Standard Time":"Pacific/Norfolk","North Asia East Standard Time":"Asia/Irkutsk","North Asia Standard Time":"Asia/Krasnoyarsk","North Korea Standard Time":"Asia/Pyongyang","Omsk Standard Time":"Asia/Omsk","Pacific SA Standard Time":"America/Santiago","Pacific Standard Time":"America/Los_Angeles","Pacific Standard Time (Mexico)":"America/Tijuana","Pakistan Standard Time":"Asia/Karachi","Paraguay Standard Time":"America/Asuncion","Qyzylorda Standard Time":"Asia/Qyzylorda","Romance Standard Time":"Europe/Paris","Russia Time Zone 10":"Asia/Srednekolymsk","Russia Time Zone 11":"Asia/Kamchatka","Russia Time Zone 3":"Europe/Samara","Russian Standard Time":"Europe/Moscow","SA Eastern Standard Time":"America/Cayenne","SA Pacific Standard Time":"America/Bogota","SA Western Standard Time":"America/La_Paz","SE Asia Standard Time":"Asia/Bangkok","Saint Pierre Standard Time":"America/Miquelon","Sakhalin Standard Time":"Asia/Sakhalin","Samoa Standard Time":"Pacific/Apia","Sao Tome Standard Time":"Africa/Sao_Tome","Saratov Standard Time":"Europe/Saratov","Singapore Standard Time":"Asia/Singapore","South Africa Standard Time":"Africa/Johannesburg","South Sudan Standard Time":"Africa/Juba","Sri Lanka Standard Time":"Asia/Colombo","Sudan Standard Time":"Africa/Khartoum","Syria Standard Time":"Asia/Damascus","Taipei Standard Time":"Asia/Taipei","Tasmania Standard Time":"Australia/Hobart","Tocantins Standard Time":"America/Araguaina","Tokyo Standard Time":"Asia/Tokyo","Tomsk Standard Time":"Asia/Tomsk","Tonga Standard Time":"Pacific/Tongatapu","Transbaikal Standard Time":"Asia/Chita","Turkey Standard Time":"Europe/Istanbul","Turks And Caicos Standard Time":"America/Grand_Turk","US Eastern Standard Time":"America/Indianapolis","US Mountain Standard Time":"America/Phoenix",UTC:"Etc/UTC","UTC+12":"Etc/GMT-12","UTC+13":"Etc/GMT-13","UTC-02":"Etc/GMT+2","UTC-08":"Etc/GMT+8","UTC-09":"Etc/GMT+9","UTC-11":"Etc/GMT+11","Ulaanbaatar Standard Time":"Asia/Ulaanbaatar","Venezuela Standard Time":"America/Caracas","Vladivostok Standard Time":"Asia/Vladivostok","Volgograd Standard Time":"Europe/Volgograd","W. Australia Standard Time":"Australia/Perth","W. Central Africa Standard Time":"Africa/Lagos","W. Europe Standard Time":"Europe/Berlin","W. Mongolia Standard Time":"Asia/Hovd","West Asia Standard Time":"Asia/Tashkent","West Bank Standard Time":"Asia/Hebron","West Pacific Standard Time":"Pacific/Port_Moresby","Yakutsk Standard Time":"Asia/Yakutsk","Yukon Standard Time":"America/Whitehorse"};
|
|
1
|
+
"use strict";export const WINDOWS_TO_IANA={"AUS Central Standard Time":"Australia/Darwin","AUS Eastern Standard Time":"Australia/Sydney","Afghanistan Standard Time":"Asia/Kabul","Alaskan Standard Time":"America/Anchorage","Aleutian Standard Time":"America/Adak","Altai Standard Time":"Asia/Barnaul","Arab Standard Time":"Asia/Riyadh","Arabian Standard Time":"Asia/Dubai","Arabic Standard Time":"Asia/Baghdad","Argentina Standard Time":"America/Buenos_Aires","Astrakhan Standard Time":"Europe/Astrakhan","Atlantic Standard Time":"America/Halifax","Aus Central W. Standard Time":"Australia/Eucla","Azerbaijan Standard Time":"Asia/Baku","Azores Standard Time":"Atlantic/Azores","Bahia Standard Time":"America/Bahia","Bangladesh Standard Time":"Asia/Dhaka","Belarus Standard Time":"Europe/Minsk","Bougainville Standard Time":"Pacific/Bougainville","Canada Central Standard Time":"America/Regina","Cape Verde Standard Time":"Atlantic/Cape_Verde","Caucasus Standard Time":"Asia/Yerevan","Cen. Australia Standard Time":"Australia/Adelaide","Central America Standard Time":"America/Guatemala","Central Asia Standard Time":"Asia/Almaty","Central Brazilian Standard Time":"America/Cuiaba","Central Europe Standard Time":"Europe/Budapest","Central European Standard Time":"Europe/Warsaw","Central Pacific Standard Time":"Pacific/Guadalcanal","Central Standard Time":"America/Chicago","Central Standard Time (Mexico)":"America/Mexico_City","Chatham Islands Standard Time":"Pacific/Chatham","China Standard Time":"Asia/Shanghai","Cuba Standard Time":"America/Havana","Dateline Standard Time":"Etc/GMT+12","E. Africa Standard Time":"Africa/Nairobi","E. Australia Standard Time":"Australia/Brisbane","E. Europe Standard Time":"Europe/Chisinau","E. South America Standard Time":"America/Sao_Paulo","Easter Island Standard Time":"Pacific/Easter","Eastern Standard Time":"America/New_York","Eastern Standard Time (Mexico)":"America/Cancun","Egypt Standard Time":"Africa/Cairo","Ekaterinburg Standard Time":"Asia/Yekaterinburg","FLE Standard Time":"Europe/Kiev","Fiji Standard Time":"Pacific/Fiji","GMT Standard Time":"Europe/London","GTB Standard Time":"Europe/Bucharest","Georgian Standard Time":"Asia/Tbilisi","Greenland Standard Time":"America/Godthab","Greenwich Standard Time":"Atlantic/Reykjavik","Haiti Standard Time":"America/Port-au-Prince","Hawaiian Standard Time":"Pacific/Honolulu","India Standard Time":"Asia/Calcutta","Iran Standard Time":"Asia/Tehran","Israel Standard Time":"Asia/Jerusalem","Jordan Standard Time":"Asia/Amman","Kaliningrad Standard Time":"Europe/Kaliningrad","Korea Standard Time":"Asia/Seoul","Libya Standard Time":"Africa/Tripoli","Line Islands Standard Time":"Pacific/Kiritimati","Lord Howe Standard Time":"Australia/Lord_Howe","Magadan Standard Time":"Asia/Magadan","Magallanes Standard Time":"America/Punta_Arenas","Marquesas Standard Time":"Pacific/Marquesas","Mauritius Standard Time":"Indian/Mauritius","Middle East Standard Time":"Asia/Beirut","Montevideo Standard Time":"America/Montevideo","Morocco Standard Time":"Africa/Casablanca","Mountain Standard Time":"America/Denver","Mountain Standard Time (Mexico)":"America/Chihuahua","Myanmar Standard Time":"Asia/Rangoon","N. Central Asia Standard Time":"Asia/Novosibirsk","Namibia Standard Time":"Africa/Windhoek","Nepal Standard Time":"Asia/Katmandu","New Zealand Standard Time":"Pacific/Auckland","Newfoundland Standard Time":"America/St_Johns","Norfolk Standard Time":"Pacific/Norfolk","North Asia East Standard Time":"Asia/Irkutsk","North Asia Standard Time":"Asia/Krasnoyarsk","North Korea Standard Time":"Asia/Pyongyang","Omsk Standard Time":"Asia/Omsk","Pacific SA Standard Time":"America/Santiago","Pacific Standard Time":"America/Los_Angeles","Pacific Standard Time (Mexico)":"America/Tijuana","Pakistan Standard Time":"Asia/Karachi","Paraguay Standard Time":"America/Asuncion","Qyzylorda Standard Time":"Asia/Qyzylorda","Romance Standard Time":"Europe/Paris","Russia Time Zone 10":"Asia/Srednekolymsk","Russia Time Zone 11":"Asia/Kamchatka","Russia Time Zone 3":"Europe/Samara","Russian Standard Time":"Europe/Moscow","SA Eastern Standard Time":"America/Cayenne","SA Pacific Standard Time":"America/Bogota","SA Western Standard Time":"America/La_Paz","SE Asia Standard Time":"Asia/Bangkok","Saint Pierre Standard Time":"America/Miquelon","Sakhalin Standard Time":"Asia/Sakhalin","Samoa Standard Time":"Pacific/Apia","Sao Tome Standard Time":"Africa/Sao_Tome","Saratov Standard Time":"Europe/Saratov","Singapore Standard Time":"Asia/Singapore","South Africa Standard Time":"Africa/Johannesburg","South Sudan Standard Time":"Africa/Juba","Sri Lanka Standard Time":"Asia/Colombo","Sudan Standard Time":"Africa/Khartoum","Syria Standard Time":"Asia/Damascus","Taipei Standard Time":"Asia/Taipei","Tasmania Standard Time":"Australia/Hobart","Tocantins Standard Time":"America/Araguaina","Tokyo Standard Time":"Asia/Tokyo","Tomsk Standard Time":"Asia/Tomsk","Tonga Standard Time":"Pacific/Tongatapu","Transbaikal Standard Time":"Asia/Chita","Turkey Standard Time":"Europe/Istanbul","Turks And Caicos Standard Time":"America/Grand_Turk","US Eastern Standard Time":"America/Indianapolis","US Mountain Standard Time":"America/Phoenix",UTC:"Etc/UTC","UTC+12":"Etc/GMT-12","UTC+13":"Etc/GMT-13","UTC-02":"Etc/GMT+2","UTC-08":"Etc/GMT+8","UTC-09":"Etc/GMT+9","UTC-11":"Etc/GMT+11","Ulaanbaatar Standard Time":"Asia/Ulaanbaatar","Venezuela Standard Time":"America/Caracas","Vladivostok Standard Time":"Asia/Vladivostok","Volgograd Standard Time":"Europe/Volgograd","W. Australia Standard Time":"Australia/Perth","W. Central Africa Standard Time":"Africa/Lagos","W. Europe Standard Time":"Europe/Berlin","W. Mongolia Standard Time":"Asia/Hovd","West Asia Standard Time":"Asia/Tashkent","West Bank Standard Time":"Asia/Hebron","West Pacific Standard Time":"Pacific/Port_Moresby","Yakutsk Standard Time":"Asia/Yakutsk","Yukon Standard Time":"America/Whitehorse"};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const toExpoOptions=
|
|
1
|
+
"use strict";const ACCURACY_BALANCED=3,ACCURACY_HIGHEST=5,toExpoOptions=t=>{const e={accuracy:t?.enableHighAccuracy?5:3};return"number"==typeof t?.distanceFilter&&(e.distanceInterval=t.distanceFilter),e},PERMISSION_PATTERN=/permission|denied|not (been )?granted|authoriz/i,SERVICES_PATTERN=/location services|provider|disabled|switched off|turned off/i,TIMEOUT_PATTERN=/time ?d? ?out|timeout/i,toNativeError=t=>{const e=t instanceof Error?t.message:String(t);return PERMISSION_PATTERN.test(e)?{code:1,message:e}:TIMEOUT_PATTERN.test(e)?{code:3,message:e}:(SERVICES_PATTERN.test(e),{code:2,message:e})},toNativePosition=t=>({coords:{latitude:t.coords?.latitude??null,longitude:t.coords?.longitude??null,accuracy:t.coords?.accuracy??null,altitude:t.coords?.altitude??null,heading:t.coords?.heading??null,speed:t.coords?.speed??null},timestamp:t.timestamp??null});export const adaptExpoLocation=t=>{const e=new Map;let o=1;return{getCurrentPosition:(e,o,i)=>{t.getCurrentPositionAsync(toExpoOptions(i)).then(t=>e(toNativePosition(t))).catch(t=>o?.(toNativeError(t)))},watchPosition:(i,n,s)=>{const r=o++;return e.set(r,null),t.watchPositionAsync(toExpoOptions(s),t=>i(toNativePosition(t))).then(t=>{e.has(r)?e.set(r,t):t.remove()}).catch(t=>{e.delete(r),n?.(toNativeError(t))}),r},clearWatch:t=>{const o=e.get(t);e.delete(t),o?.remove()}}};
|