@webority/mobile-core 0.149.0 → 0.152.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +47 -0
- package/lib/commonjs/api/baseUrl.js +1 -1
- package/lib/commonjs/api/contractCaller.js +1 -0
- package/lib/commonjs/api/curl.js +1 -1
- package/lib/commonjs/api/minAppVersion.js +1 -1
- package/lib/commonjs/api/requestDefaults.js +1 -1
- package/lib/commonjs/api/retry.js +1 -1
- package/lib/commonjs/api/tokenRefresh.js +1 -1
- package/lib/commonjs/api/userClient.js +1 -1
- package/lib/commonjs/api/workspace.js +1 -1
- package/lib/commonjs/auth/authStore.js +1 -1
- package/lib/commonjs/auth/jwt.js +1 -1
- package/lib/commonjs/deepLink/index.js +1 -1
- package/lib/commonjs/download/adapters/expoFs.js +1 -1
- package/lib/commonjs/download/index.js +1 -1
- package/lib/commonjs/errors/extractApiError.js +1 -1
- package/lib/commonjs/errors/index.js +1 -1
- package/lib/commonjs/errors/parseResponse.js +1 -0
- package/lib/commonjs/errors/requestPlatform.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 -1
- package/lib/commonjs/formatters/house.js +1 -1
- package/lib/commonjs/formatters/number.js +1 -1
- package/lib/commonjs/formatters/phone.js +1 -1
- package/lib/commonjs/geolocation/index.js +1 -1
- package/lib/commonjs/index.js +1 -1
- package/lib/commonjs/india/gstStates.js +1 -0
- package/lib/commonjs/india/index.js +1 -1
- package/lib/commonjs/jest/setup.js +1 -0
- package/lib/commonjs/logger/crashlytics.js +1 -1
- package/lib/commonjs/logger/index.js +1 -1
- package/lib/commonjs/logger/redact.js +1 -1
- package/lib/commonjs/network/networkStatus.js +1 -1
- package/lib/commonjs/outbox/outbox.js +1 -1
- package/lib/commonjs/outbox/types.js +1 -1
- package/lib/commonjs/push/broadcasts.js +1 -1
- package/lib/commonjs/push/push.js +1 -1
- package/lib/commonjs/query/apiBaseQuery.js +1 -1
- package/lib/commonjs/query/dataState.js +1 -0
- package/lib/commonjs/query/entityVersion.js +1 -0
- package/lib/commonjs/query/index.js +1 -1
- package/lib/commonjs/query/paging.js +1 -1
- package/lib/commonjs/query/persistedQueries.js +1 -1
- package/lib/commonjs/query/tags.js +1 -1
- package/lib/commonjs/query/usePagedList.js +1 -1
- package/lib/commonjs/redux/errorToastMiddleware.js +1 -1
- package/lib/commonjs/redux/rootReducer.js +1 -1
- package/lib/commonjs/redux/sessionMiddleware.js +1 -1
- package/lib/commonjs/review/index.js +1 -1
- package/lib/commonjs/secureScreen/index.js +1 -1
- package/lib/commonjs/sqlite/index.js +1 -1
- package/lib/commonjs/storage/index.js +1 -1
- package/lib/commonjs/types/complete.js +1 -0
- package/lib/commonjs/types/formData.d.js +1 -0
- package/lib/commonjs/updates/updates.js +1 -1
- package/lib/commonjs/utils/base64.js +1 -1
- package/lib/commonjs/utils/guards.js +1 -0
- package/lib/commonjs/utils/imageCompression.js +1 -1
- package/lib/module/api/baseUrl.js +1 -1
- package/lib/module/api/contractCaller.js +1 -0
- package/lib/module/api/curl.js +1 -1
- package/lib/module/api/minAppVersion.js +1 -1
- package/lib/module/api/requestDefaults.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/api/workspace.js +1 -1
- package/lib/module/auth/authStore.js +1 -1
- package/lib/module/auth/jwt.js +1 -1
- package/lib/module/deepLink/index.js +1 -1
- package/lib/module/download/adapters/expoFs.js +1 -1
- package/lib/module/download/index.js +1 -1
- package/lib/module/errors/extractApiError.js +1 -1
- package/lib/module/errors/index.js +1 -1
- package/lib/module/errors/parseResponse.js +1 -0
- package/lib/module/errors/requestPlatform.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 -1
- package/lib/module/formatters/house.js +1 -1
- package/lib/module/formatters/number.js +1 -1
- package/lib/module/formatters/phone.js +1 -1
- package/lib/module/geolocation/index.js +1 -1
- package/lib/module/index.js +1 -1
- package/lib/module/india/gstStates.js +1 -0
- package/lib/module/india/index.js +1 -1
- package/lib/module/jest/setup.js +1 -0
- 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/networkStatus.js +1 -1
- package/lib/module/outbox/outbox.js +1 -1
- package/lib/module/outbox/types.js +1 -1
- package/lib/module/push/broadcasts.js +1 -1
- package/lib/module/push/push.js +1 -1
- package/lib/module/query/apiBaseQuery.js +1 -1
- package/lib/module/query/dataState.js +1 -0
- package/lib/module/query/entityVersion.js +1 -0
- package/lib/module/query/index.js +1 -1
- package/lib/module/query/paging.js +1 -1
- package/lib/module/query/persistedQueries.js +1 -1
- package/lib/module/query/tags.js +1 -1
- package/lib/module/query/usePagedList.js +1 -1
- package/lib/module/redux/errorToastMiddleware.js +1 -1
- package/lib/module/redux/rootReducer.js +1 -1
- package/lib/module/redux/sessionMiddleware.js +1 -1
- package/lib/module/review/index.js +1 -1
- package/lib/module/secureScreen/index.js +1 -1
- package/lib/module/sqlite/index.js +1 -1
- package/lib/module/storage/index.js +1 -1
- package/lib/module/types/complete.js +1 -0
- package/lib/module/types/formData.d.js +1 -0
- package/lib/module/updates/updates.js +1 -1
- package/lib/module/utils/base64.js +1 -1
- package/lib/module/utils/guards.js +1 -0
- package/lib/module/utils/imageCompression.js +1 -1
- package/lib/typescript/commonjs/api/clientHeaders.d.ts +1 -1
- package/lib/typescript/commonjs/api/contractCaller.d.ts +7 -0
- package/lib/typescript/commonjs/api/fetchRetry.d.ts +3 -3
- package/lib/typescript/commonjs/api/minAppVersion.d.ts +1 -1
- package/lib/typescript/commonjs/api/retry.d.ts +11 -5
- package/lib/typescript/commonjs/api/tokenRefresh.d.ts +2 -1
- package/lib/typescript/commonjs/api/userClient.d.ts +11 -0
- package/lib/typescript/commonjs/api/workspace.d.ts +3 -3
- package/lib/typescript/commonjs/appLock/index.d.ts +1 -1
- package/lib/typescript/commonjs/attachments/index.d.ts +5 -5
- package/lib/typescript/commonjs/auth/authStore.d.ts +8 -6
- package/lib/typescript/commonjs/auth/jwt.d.ts +11 -8
- package/lib/typescript/commonjs/deepLink/index.d.ts +18 -11
- package/lib/typescript/commonjs/download/adapters/expoFs.d.ts +4 -4
- package/lib/typescript/commonjs/download/index.d.ts +16 -12
- package/lib/typescript/commonjs/errors/extractApiError.d.ts +9 -17
- package/lib/typescript/commonjs/errors/index.d.ts +2 -0
- package/lib/typescript/commonjs/errors/parseResponse.d.ts +20 -0
- package/lib/typescript/commonjs/errors/requestPlatform.d.ts +8 -0
- package/lib/typescript/commonjs/formatters/currency.d.ts +5 -5
- package/lib/typescript/commonjs/formatters/dateMath.d.ts +2 -2
- package/lib/typescript/commonjs/formatters/formatConfig.d.ts +8 -6
- package/lib/typescript/commonjs/formatters/house.d.ts +19 -20
- package/lib/typescript/commonjs/formatters/intlCache.d.ts +1 -3
- package/lib/typescript/commonjs/formatters/phone.d.ts +3 -3
- package/lib/typescript/commonjs/geolocation/adapters/expoLocation.d.ts +11 -11
- package/lib/typescript/commonjs/geolocation/index.d.ts +29 -26
- package/lib/typescript/commonjs/index.d.ts +5 -2
- package/lib/typescript/commonjs/india/gstStates.d.ts +8 -0
- package/lib/typescript/commonjs/india/gstStates.g.d.ts +1 -1
- package/lib/typescript/commonjs/india/index.d.ts +1 -0
- package/lib/typescript/commonjs/initSDK.d.ts +14 -14
- package/lib/typescript/commonjs/initUserAuth.d.ts +9 -8
- package/lib/typescript/commonjs/jest/setup.d.ts +9 -0
- package/lib/typescript/commonjs/logger/crashlytics.d.ts +5 -4
- package/lib/typescript/commonjs/logger/index.d.ts +19 -19
- package/lib/typescript/commonjs/logger/redact.d.ts +3 -1
- package/lib/typescript/commonjs/metro/types.d.ts +4 -4
- package/lib/typescript/commonjs/network/networkStatus.d.ts +1 -1
- package/lib/typescript/commonjs/outbox/types.d.ts +6 -17
- package/lib/typescript/commonjs/permissions/index.d.ts +7 -4
- package/lib/typescript/commonjs/pickers/index.d.ts +18 -18
- package/lib/typescript/commonjs/push/push.d.ts +23 -23
- package/lib/typescript/commonjs/query/apiBaseQuery.d.ts +23 -14
- package/lib/typescript/commonjs/query/dataState.d.ts +76 -0
- package/lib/typescript/commonjs/query/entityVersion.d.ts +47 -0
- package/lib/typescript/commonjs/query/index.d.ts +5 -1
- package/lib/typescript/commonjs/query/paging.d.ts +6 -5
- package/lib/typescript/commonjs/query/persistedQueries.d.ts +12 -7
- package/lib/typescript/commonjs/query/usePagedList.d.ts +11 -18
- package/lib/typescript/commonjs/redux/errorToastMiddleware.d.ts +4 -4
- package/lib/typescript/commonjs/redux/rootReducer.d.ts +1 -1
- package/lib/typescript/commonjs/review/index.d.ts +1 -1
- package/lib/typescript/commonjs/secureScreen/index.d.ts +1 -1
- package/lib/typescript/commonjs/share/index.d.ts +2 -2
- package/lib/typescript/commonjs/sqlite/index.d.ts +21 -16
- package/lib/typescript/commonjs/storage/index.d.ts +9 -9
- package/lib/typescript/commonjs/types/axios.d.ts +10 -2
- package/lib/typescript/commonjs/types/complete.d.ts +5 -0
- package/lib/typescript/commonjs/updates/updates.d.ts +20 -20
- package/lib/typescript/commonjs/utils/guards.d.ts +9 -0
- package/lib/typescript/commonjs/utils/imageCompression.d.ts +9 -9
- package/lib/typescript/commonjs/validators/index.d.ts +5 -5
- package/lib/typescript/commonjs/versionCheck/appBuild.d.ts +3 -2
- package/lib/typescript/commonjs/versionCheck/index.d.ts +4 -4
- package/lib/typescript/module/api/clientHeaders.d.ts +1 -1
- package/lib/typescript/module/api/contractCaller.d.ts +7 -0
- package/lib/typescript/module/api/fetchRetry.d.ts +3 -3
- package/lib/typescript/module/api/minAppVersion.d.ts +1 -1
- package/lib/typescript/module/api/retry.d.ts +11 -5
- package/lib/typescript/module/api/tokenRefresh.d.ts +2 -1
- package/lib/typescript/module/api/userClient.d.ts +11 -0
- package/lib/typescript/module/api/workspace.d.ts +3 -3
- package/lib/typescript/module/appLock/index.d.ts +1 -1
- package/lib/typescript/module/attachments/index.d.ts +5 -5
- package/lib/typescript/module/auth/authStore.d.ts +8 -6
- package/lib/typescript/module/auth/jwt.d.ts +11 -8
- package/lib/typescript/module/deepLink/index.d.ts +18 -11
- package/lib/typescript/module/download/adapters/expoFs.d.ts +4 -4
- package/lib/typescript/module/download/index.d.ts +16 -12
- package/lib/typescript/module/errors/extractApiError.d.ts +9 -17
- package/lib/typescript/module/errors/index.d.ts +2 -0
- package/lib/typescript/module/errors/parseResponse.d.ts +20 -0
- package/lib/typescript/module/errors/requestPlatform.d.ts +8 -0
- package/lib/typescript/module/formatters/currency.d.ts +5 -5
- package/lib/typescript/module/formatters/dateMath.d.ts +2 -2
- package/lib/typescript/module/formatters/formatConfig.d.ts +8 -6
- package/lib/typescript/module/formatters/house.d.ts +19 -20
- package/lib/typescript/module/formatters/intlCache.d.ts +1 -3
- package/lib/typescript/module/formatters/phone.d.ts +3 -3
- package/lib/typescript/module/geolocation/adapters/expoLocation.d.ts +11 -11
- package/lib/typescript/module/geolocation/index.d.ts +29 -26
- package/lib/typescript/module/index.d.ts +5 -2
- package/lib/typescript/module/india/gstStates.d.ts +8 -0
- package/lib/typescript/module/india/gstStates.g.d.ts +1 -1
- package/lib/typescript/module/india/index.d.ts +1 -0
- package/lib/typescript/module/initSDK.d.ts +14 -14
- package/lib/typescript/module/initUserAuth.d.ts +9 -8
- package/lib/typescript/module/jest/setup.d.ts +9 -0
- package/lib/typescript/module/logger/crashlytics.d.ts +5 -4
- package/lib/typescript/module/logger/index.d.ts +19 -19
- package/lib/typescript/module/logger/redact.d.ts +3 -1
- package/lib/typescript/module/metro/types.d.ts +4 -4
- package/lib/typescript/module/network/networkStatus.d.ts +1 -1
- package/lib/typescript/module/outbox/types.d.ts +6 -17
- package/lib/typescript/module/permissions/index.d.ts +7 -4
- package/lib/typescript/module/pickers/index.d.ts +18 -18
- package/lib/typescript/module/push/push.d.ts +23 -23
- package/lib/typescript/module/query/apiBaseQuery.d.ts +23 -14
- package/lib/typescript/module/query/dataState.d.ts +76 -0
- package/lib/typescript/module/query/entityVersion.d.ts +47 -0
- package/lib/typescript/module/query/index.d.ts +5 -1
- package/lib/typescript/module/query/paging.d.ts +6 -5
- package/lib/typescript/module/query/persistedQueries.d.ts +12 -7
- package/lib/typescript/module/query/usePagedList.d.ts +11 -18
- package/lib/typescript/module/redux/errorToastMiddleware.d.ts +4 -4
- package/lib/typescript/module/redux/rootReducer.d.ts +1 -1
- package/lib/typescript/module/review/index.d.ts +1 -1
- package/lib/typescript/module/secureScreen/index.d.ts +1 -1
- package/lib/typescript/module/share/index.d.ts +2 -2
- package/lib/typescript/module/sqlite/index.d.ts +21 -16
- package/lib/typescript/module/storage/index.d.ts +9 -9
- package/lib/typescript/module/types/axios.d.ts +10 -2
- package/lib/typescript/module/types/complete.d.ts +5 -0
- package/lib/typescript/module/updates/updates.d.ts +20 -20
- package/lib/typescript/module/utils/guards.d.ts +9 -0
- package/lib/typescript/module/utils/imageCompression.d.ts +9 -9
- package/lib/typescript/module/validators/index.d.ts +5 -5
- package/lib/typescript/module/versionCheck/appBuild.d.ts +3 -2
- package/lib/typescript/module/versionCheck/index.d.ts +4 -4
- package/package.json +14 -2
- package/src/specs/NativeSmsRetriever.ts +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{combineReducers,createAction}from"@reduxjs/toolkit";export const resetState=createAction("app/resetState");export function createRootReducer(e,t={}){const r=combineReducers(e),o=t.preserve??[];return(e,t)=>{if(void 0!==e&&resetState.match(t)){const c=
|
|
1
|
+
"use strict";import{combineReducers,createAction}from"@reduxjs/toolkit";export const resetState=createAction("app/resetState");export function createRootReducer(e,t={}){const r=combineReducers(e),o=t.preserve??[];return(e,t)=>{if(void 0!==e&&resetState.match(t)){const c=r(void 0,t);for(const t of o)c[t]=e[t];return c}return r(e,t)}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const isAction=e=>"object"==typeof e&&null!==e&&"type"in e,thunkMeta=e=>isAction(e)&&
|
|
1
|
+
"use strict";import{isRecord}from"../utils/guards.js";const isAction=e=>"object"==typeof e&&null!==e&&"type"in e,thunkMeta=e=>isAction(e)&&isRecord(e.meta)?e.meta:{};export const createSessionMiddleware=e=>{const t=new Set,n=new Set;return()=>s=>r=>{const{requestId:i,requestStatus:o}=thunkMeta(r);if(!i||!o)return s(r);if("pending"===o){if(isAction(r)&&e.isSignOut(r)){for(const e of t)n.add(e);t.clear()}else t.add(i);return s(r)}return t.delete(i),n.delete(i)?r:s(r)}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{Logger}from"../logger/index.js";import{Storage}from"../storage/index.js";const TAG="[reviewPrompt]",DAY_MS=864e5;export const DEFAULT_REVIEW_COOL_DOWN_DAYS=90;export const REVIEW_PROMPT_STORAGE_KEY="@webority/review-prompt";const storeReview=()=>require("expo-store-review");let coolDownDays=90,inFlight=!1;export const configureReviewPrompt=(e={})=>{const o=e.coolDownDays??90;if(!Number.isFinite(o)||o<0)throw new Error(`[@webority/mobile-core] configureReviewPrompt: coolDownDays must be a number of days, 0 or more; got ${String(o)}.`);o<90&&Logger.warn(`${TAG} coolDownDays ${o} is under the 90-day minimum for store builds.`),coolDownDays=o};const withinCoolDown=(e,o)=>{if(!e)return!1;const t=Date.parse(e.lastAskedUtc);return!Number.isNaN(t)&&o-t<coolDownDays*DAY_MS},storeCanPrompt=async()=>{try{const e=storeReview();return await e.isAvailableAsync()&&await e.hasAction()}catch(e){return Logger.warn(`${TAG} the store review module is not available`,e),!1}};export const requestReviewAfterSuccess=async e=>{if(inFlight)return"skipped-cooldown";inFlight=!0;try{const o=await Storage.getJson("@webority/review-prompt"),t=Date.now();if(withinCoolDown(o,t))return"skipped-cooldown";if(!await storeCanPrompt())return"skipped-unavailable";try{await storeReview().requestReview()}catch(o){return Logger.warn(`${TAG} the store review request failed after "${e}"`,o),"skipped-unavailable"}const r={lastAskedUtc:new Date(t).toISOString(),moment:e};return await Storage.setJson("@webority/review-prompt",r)||Logger.warn(`${TAG} the prompt time could not be stored, so the cool-down may not hold`),Logger.info(`${TAG} review prompt requested after "${e}"`),"shown"}finally{inFlight=!1}};
|
|
1
|
+
"use strict";import{Logger}from"../logger/index.js";import{Storage}from"../storage/index.js";import{isRecord}from"../utils/guards.js";const TAG="[reviewPrompt]",DAY_MS=864e5;export const DEFAULT_REVIEW_COOL_DOWN_DAYS=90;export const REVIEW_PROMPT_STORAGE_KEY="@webority/review-prompt";const storeReview=()=>require("expo-store-review");let coolDownDays=90,inFlight=!1;export const configureReviewPrompt=(e={})=>{const o=e.coolDownDays??90;if(!Number.isFinite(o)||o<0)throw new Error(`[@webority/mobile-core] configureReviewPrompt: coolDownDays must be a number of days, 0 or more; got ${String(o)}.`);o<90&&Logger.warn(`${TAG} coolDownDays ${o} is under the 90-day minimum for store builds.`),coolDownDays=o};const parseReviewPromptRecord=e=>isRecord(e)&&"string"==typeof e.lastAskedUtc&&"string"==typeof e.moment?{lastAskedUtc:e.lastAskedUtc,moment:e.moment}:null,withinCoolDown=(e,o)=>{if(!e)return!1;const t=Date.parse(e.lastAskedUtc);return!Number.isNaN(t)&&o-t<coolDownDays*DAY_MS},storeCanPrompt=async()=>{try{const e=storeReview();return await e.isAvailableAsync()&&await e.hasAction()}catch(e){return Logger.warn(`${TAG} the store review module is not available`,e),!1}};export const requestReviewAfterSuccess=async e=>{if(inFlight)return"skipped-cooldown";inFlight=!0;try{const o=await Storage.getJson("@webority/review-prompt",parseReviewPromptRecord),t=Date.now();if(withinCoolDown(o,t))return"skipped-cooldown";if(!await storeCanPrompt())return"skipped-unavailable";try{await storeReview().requestReview()}catch(o){return Logger.warn(`${TAG} the store review request failed after "${e}"`,o),"skipped-unavailable"}const r={lastAskedUtc:new Date(t).toISOString(),moment:e};return await Storage.setJson("@webority/review-prompt",r)||Logger.warn(`${TAG} the prompt time could not be stored, so the cool-down may not hold`),Logger.info(`${TAG} review prompt requested after "${e}"`),"shown"}finally{inFlight=!1}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{useEffect,
|
|
1
|
+
"use strict";import{useEffect,useState}from"react";import{Platform}from"react-native";import{Logger}from"../logger/index.js";const screenCapture=()=>require("expo-screen-capture"),report=e=>r=>{Logger.error(`[@webority/mobile-core] useSecureScreen could not ${e}.`,r)},protectionFailed=(e,r)=>t=>{report(e)(t),r(new Error(`[@webority/mobile-core] useSecureScreen could not ${e}, so the screen is not protected.`,{cause:t}))};let nextKey=0,appSwitcherHolders=0;export const useSecureScreen=(e={})=>{const{focused:r=!0}=e,[t]=useState(()=>(nextKey+=1,`webority-secure-screen-${nextKey}`)),[c,o]=useState(null);if(useEffect(()=>{if(!r)return;const e=screenCapture();e.preventScreenCaptureAsync(t).catch(protectionFailed("block screen capture",o));const c="ios"===Platform.OS;return c&&(appSwitcherHolders+=1,1===appSwitcherHolders&&e.enableAppSwitcherProtectionAsync().catch(protectionFailed("hide the app switcher snapshot",o))),()=>{e.allowScreenCaptureAsync(t).catch(report("release screen capture")),c&&(appSwitcherHolders-=1,0===appSwitcherHolders&&e.disableAppSwitcherProtectionAsync().catch(report("restore the app switcher snapshot")))}},[r,t]),c)throw c};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import*as ExpoSqlite from"expo-sqlite";import{Logger}from"../logger/index.js";import{adaptExpoSqlite}from"./adapters/expo.js";let expoDriver,backend=null;export const setSqliteImplementation=e=>{backend=e};const hasNativeSqlite=e=>"function"==typeof e?.openDatabaseAsync,resolveDriver=()=>{if(backend)return backend;if(void 0===expoDriver){const e=ExpoSqlite;expoDriver=hasNativeSqlite(e)?adaptExpoSqlite(e):null}return expoDriver};export const isSqliteAvailable=()=>null!==resolveDriver();const requireBackend=e=>{const t=resolveDriver();if(!t){const t=new Error(`[@webority/mobile-core] No SQLite driver available; cannot ${e}. Install expo-sqlite (the only sanctioned driver) in the consuming app.`);throw Logger.error(t.message),t}return t};export const MIGRATIONS_TABLE="_webority_migrations";const IDENTIFIER=/^[A-Za-z_][A-Za-z0-9_]*$/;export const assertSqlIdentifier=(e,t="identifier")=>{if("string"!=typeof e||!IDENTIFIER.test(e))throw new Error(`[@webority/mobile-core] Invalid SQL ${t} ${JSON.stringify(e)}. Only letters, digits and underscores are allowed, and it must not start with a digit. Pass values as bound parameters instead of building them into the name.`);return e};const quoteIdentifier=(e,t="identifier")=>`"${assertSqlIdentifier(e,t)}"`,escapeIdentifier=e=>`"${e.replace(/"/g,'""')}"`,COLUMN_DEFINITION=/^[A-Za-z0-9_ ,.()'"+*/=<>|%:$-]+$/,assertColumnDefinition=(e,t)=>{const r="string"==typeof e?e.trim():"";if(0===r.length||!COLUMN_DEFINITION.test(r)||r.includes("--"))throw new Error(`[@webority/mobile-core] Invalid column definition for "${t}": ${JSON.stringify(e)}. A definition is raw SQL such as 'INTEGER NOT NULL DEFAULT 0' and may not contain a statement separator or a comment.`);return r};export const toSqliteValue=e=>void 0===e?null:"boolean"==typeof e?e?1:0:e instanceof Date?e.toISOString():e;export const fromSqliteBoolean=e=>{if("boolean"==typeof e)return e;if("number"==typeof e)return 0!==e;if("string"==typeof e){const t=e.trim().toLowerCase();return"1"===t||"true"===t}return!1};export const whereIn=(e,t)=>{const r=quoteIdentifier(e,"column name");return 0===t.length?{sql:"1 = 0",params:[]}:{sql:`${r} IN (${t.map(()=>"?").join(", ")})`,params:t.map(toSqliteValue)}};const isRawWhere=e=>"string"==typeof e.sql&&Object.keys(e).every(e=>"sql"===e||"params"===e),buildWhere=e=>{if(!e)return{clause:"",params:[]};if(isRawWhere(e)){const t=e.sql.trim();return 0===t.length?{clause:"",params:[]}:{clause:` WHERE ${t}`,params:[...e.params??[]]}}const t=Object.entries(e);if(0===t.length)return{clause:"",params:[]};const r=[],n=[];for(const[e,i]of t){const t=quoteIdentifier(e,"column name"),o=toSqliteValue(i);null===o?r.push(`${t} IS NULL`):(r.push(`${t} = ?`),n.push(o))}return{clause:` WHERE ${r.join(" AND ")}`,params:n}},buildOrderBy=e=>{if(void 0===e)return"";const t=e.split(",").map(e=>e.trim()).filter(e=>e.length>0);if(0===t.length)return"";return` ORDER BY ${t.map(t=>{const[r,n,...i]=t.split(/\s+/);if(i.length>0)throw new Error(`[@webority/mobile-core] Invalid orderBy term ${JSON.stringify(t)}. Expected a column name optionally followed by ASC or DESC.`);const o=quoteIdentifier(r,"orderBy column");if(void 0===n)return o;const a=n.toUpperCase();if("ASC"!==a&&"DESC"!==a)throw new Error(`[@webority/mobile-core] Invalid sort direction ${JSON.stringify(n)} in orderBy ${JSON.stringify(e)}. Expected ASC or DESC.`);return`${o} ${a}`}).join(", ")}`},assertNonNegativeInteger=(e,t)=>{if(!Number.isInteger(e)||e<0)throw new Error(`[@webority/mobile-core] Invalid ${t} ${JSON.stringify(e)}. Expected a non-negative integer.`);return e},hashString=e=>{let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return`${t.toString(16).padStart(8,"0")}-${e.length.toString(16)}`},migrationChecksum=e=>{if("function"==typeof e.up)return hashString("fn");const t=Array.isArray(e.up)?e.up.join("\n"):e.up;return hashString(t)};export const DEFAULT_PRAGMAS={journal_mode:"WAL",synchronous:"NORMAL",foreign_keys:"ON",busy_timeout:5e3};const PRAGMA_VALUE=/^[A-Za-z0-9_-]+$/,renderPragmaValue=(e,t)=>{if("number"==typeof t){if(!Number.isFinite(t))throw new Error(`[@webority/mobile-core] Invalid value for PRAGMA ${e}: ${t}.`);return String(t)}if(!PRAGMA_VALUE.test(t))throw new Error(`[@webority/mobile-core] Invalid value ${JSON.stringify(t)} for PRAGMA ${e}. PRAGMA values cannot be bound, so only letters, digits, underscores and hyphens are accepted.`);return t},queriesOver=e=>{const select=async(t,r)=>(await e(t,r)).rows;return{execute:e,select:select,selectOne:async(e,t)=>{const[r]=await select(e,t);return r??null}}},createDb=(e,t)=>{let r=Promise.resolve();const exclusive=e=>{const t=r.then(e);return r=t.catch(()=>{}),t},run=async(e,r)=>{try{return await t.execute(e,r)}catch(t){throw Logger.error(`[@webority/mobile-core] SQLite execute failed: ${e}`,t),t}},n=queriesOver(run),{execute:i,select:o,selectOne:a}=queriesOver((e,t)=>exclusive(()=>run(e,t))),runTransaction=async e=>{let r=!0;const n=queriesOver((e,t)=>r?run(e,t):Promise.reject(new Error("[@webority/mobile-core] A transaction handle was used after its transaction ended. Use the database itself outside transaction().")));try{let r;await t.execute("BEGIN");try{r=await e(n)}catch(e){try{await t.execute("ROLLBACK")}catch(e){Logger.error("[@webority/mobile-core] SQLite ROLLBACK failed",e)}throw e}try{await t.execute("COMMIT")}catch(e){try{await t.execute("ROLLBACK")}catch(e){Logger.error("[@webority/mobile-core] SQLite ROLLBACK after a failed COMMIT failed",e)}throw e}return r}finally{r=!1}},transaction=e=>exclusive(()=>runTransaction(e)),insertSql=(e,t)=>{const r=quoteIdentifier(e,"table name"),n=Object.entries(t);if(0===n.length)throw new Error(`[@webority/mobile-core] Cannot insert an empty row into ${e}. Pass at least one column.`);const i=n.map(([e])=>quoteIdentifier(e,"column name")),o=n.map(()=>"?");return{sql:`INSERT INTO ${r} (${i.join(", ")}) VALUES (${o.join(", ")})`,params:n.map(([,e])=>toSqliteValue(e))}},findAll=async(e,t,r)=>{const n=quoteIdentifier(e,"table name"),i=buildWhere(t),a=[...i.params];let s=`SELECT * FROM ${n}${i.clause}${buildOrderBy(r?.orderBy)}`;return void 0!==r?.limit?(assertNonNegativeInteger(r.limit,"limit"),s+=" LIMIT ?",a.push(r.limit)):void 0!==r?.offset&&(s+=" LIMIT -1"),void 0!==r?.offset&&(assertNonNegativeInteger(r.offset,"offset"),s+=" OFFSET ?",a.push(r.offset)),o(s,a)},ensureLedger=async()=>{await i(`CREATE TABLE IF NOT EXISTS ${escapeIdentifier(MIGRATIONS_TABLE)} (version INTEGER PRIMARY KEY, name TEXT, applied_at TEXT NOT NULL, checksum TEXT NOT NULL)`)},s=`INSERT OR REPLACE INTO ${escapeIdentifier(MIGRATIONS_TABLE)} (version, name, applied_at, checksum) VALUES (?, ?, ?, ?)`,wipe=()=>exclusive(async()=>{const e=await n.selectOne("PRAGMA foreign_keys"),t=1===Number(e?.foreign_keys??0);await run("PRAGMA foreign_keys = OFF");try{await runTransaction(async e=>{const t=await e.select("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name <> ?",[MIGRATIONS_TABLE]);for(const r of t)await e.execute(`DELETE FROM ${escapeIdentifier(r.name)}`)})}finally{await run("PRAGMA foreign_keys = "+(t?"ON":"OFF"))}}),migrate=async(t,r)=>{const n=new Set;for(const r of t){if(n.has(r.version))throw new Error(`[@webority/mobile-core] Duplicate migration version ${r.version} for database "${e}".`);n.add(r.version)}const i=await a("PRAGMA user_version");let c=Number(i?.user_version??0);if(t.length>0&&!r?.allowDowngrade){const r=t.reduce((e,t)=>Math.max(e,t.version),0);if(c>r)throw new Error(`[@webority/mobile-core] Database "${e}" is at schema version ${c}, which is newer than the highest migration supplied (${r}). This build would run old code against a newer schema. Ship the missing migrations, or pass { allowDowngrade: true } if this build is known to be compatible.`)}await ensureLedger();const l=await o(`SELECT version, checksum FROM ${escapeIdentifier(MIGRATIONS_TABLE)}`),u=new Map(l.map(e=>[Number(e.version),String(e.checksum)]));for(const r of t){if(r.version>c)continue;const t=u.get(r.version);if(void 0===t)continue;const n=migrationChecksum(r);if(t!==n)throw new Error(`[@webority/mobile-core] Migration ${r.version} has changed since it was applied to database "${e}" (recorded ${t}, now ${n}). A released migration must never be edited; add a new one instead.`)}const m=t.filter(e=>e.version>c).sort((e,t)=>e.version-t.version);for(const e of m){const t=migrationChecksum(e);await transaction(async r=>{if("function"==typeof e.up)await e.up(r);else{const t=Array.isArray(e.up)?e.up:[e.up];for(const e of t)await r.execute(e)}await r.execute(s,[e.version,e.name??null,(new Date).toISOString(),t]),await r.execute(`PRAGMA user_version = ${e.version}`)}),c=e.version}return c};return{name:e,execute:i,select:o,selectOne:a,transaction:transaction,insert:async(e,t)=>{const{sql:r,params:n}=insertSql(e,t);return(await i(r,n)).insertId},insertMany:async(e,t)=>{if(0===t.length)return 0;const r=t.map(t=>insertSql(e,t));return await transaction(async e=>{for(const t of r)await e.execute(t.sql,t.params)}),t.length},update:async(e,t,r)=>{const n=quoteIdentifier(e,"table name"),o=Object.entries(t);if(0===o.length)throw new Error(`[@webority/mobile-core] Cannot update ${e} with no values. Pass at least one column to set.`);const a=o.map(([e])=>`${quoteIdentifier(e,"column name")} = ?`),s=o.map(([,e])=>toSqliteValue(e)),c=buildWhere(r);return(await i(`UPDATE ${n} SET ${a.join(", ")}${c.clause}`,[...s,...c.params])).rowsAffected},remove:async(e,t)=>{const r=quoteIdentifier(e,"table name"),n=buildWhere(t);return(await i(`DELETE FROM ${r}${n.clause}`,n.params)).rowsAffected},upsert:async(e,t,r)=>{if(0===r.length)throw new Error(`[@webority/mobile-core] upsert on ${e} needs at least one conflict column; without one SQLite has no key to match an existing row on.`);const{sql:n,params:o}=insertSql(e,t),a=new Set(r),s=r.map(e=>quoteIdentifier(e,"column name")),c=Object.keys(t).filter(e=>!a.has(e)).map(e=>{const t=quoteIdentifier(e,"column name");return`${t} = excluded.${t}`}),l=c.length>0?`DO UPDATE SET ${c.join(", ")}`:"DO NOTHING";await i(`${n} ON CONFLICT (${s.join(", ")}) ${l}`,o)},findAll:findAll,findOne:async(e,t)=>{const[r]=await findAll(e,t,{limit:1});return r??null},count:async(e,t)=>{const r=quoteIdentifier(e,"table name"),n=buildWhere(t),i=await a(`SELECT COUNT(*) AS cnt FROM ${r}${n.clause}`,n.params);return Number(i?.cnt??0)},tableExists:async e=>{assertSqlIdentifier(e,"table name");return null!==await a("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?",[e])},createTable:async(e,t,r)=>{const n=quoteIdentifier(e,"table name"),o=Object.entries(t);if(0===o.length)throw new Error(`[@webority/mobile-core] Cannot create table ${e} with no columns.`);const a=o.map(([e,t])=>`${quoteIdentifier(e,"column name")} ${assertColumnDefinition(t,e)}`),s=!1===r?.ifNotExists?"":"IF NOT EXISTS ";await i(`CREATE TABLE ${s}${n} (${a.join(", ")})`)},dropTable:async(e,t)=>{const r=quoteIdentifier(e,"table name"),n=!1===t?.ifExists?"":"IF EXISTS ";await i(`DROP TABLE ${n}${r}`)},wipe:wipe,reset:async e=>(await wipe(),await ensureLedger(),await transaction(async e=>{await e.execute(`DELETE FROM ${escapeIdentifier(MIGRATIONS_TABLE)}`),await e.execute("PRAGMA user_version = 0")}),migrate(e)),migrate:migrate,baseline:async(e,t)=>{assertNonNegativeInteger(e,"baseline version"),await ensureLedger();const r=(new Date).toISOString();await transaction(async n=>{for(const i of t??[])i.version>e||await n.execute(s,[i.version,i.name??null,r,migrationChecksum(i)]);await n.execute(`PRAGMA user_version = ${e}`)})},close:()=>exclusive(()=>t.close())}};export const openDatabase=async(e,t)=>{const r=requireBackend("open"),n=await r.open(e,t?{location:t.location}:void 0),i=createDb(e,n);if(!1!==t?.pragmas){const e={...DEFAULT_PRAGMAS,...t?.pragmas??{}};for(const[t,r]of Object.entries(e))assertSqlIdentifier(t,"PRAGMA name"),await i.execute(`PRAGMA ${t} = ${renderPragmaValue(t,r)}`)}return i};
|
|
1
|
+
"use strict";import*as ExpoSqlite from"expo-sqlite";import{Logger}from"../logger/index.js";import{isRecord}from"../utils/guards.js";import{adaptExpoSqlite}from"./adapters/expo.js";let expoDriver,backend=null;export const setSqliteImplementation=e=>{backend=e};const hasNativeSqlite=e=>isRecord(e)&&"function"==typeof e.openDatabaseAsync,resolveDriver=()=>backend||(void 0===expoDriver&&(expoDriver=hasNativeSqlite(ExpoSqlite)?adaptExpoSqlite(ExpoSqlite):null),expoDriver);export const isSqliteAvailable=()=>null!==resolveDriver();const requireBackend=e=>{const t=resolveDriver();if(!t){const t=new Error(`[@webority/mobile-core] No SQLite driver available; cannot ${e}. Install expo-sqlite (the only sanctioned driver) in the consuming app.`);throw Logger.error(t.message),t}return t};export const MIGRATIONS_TABLE="_webority_migrations";const IDENTIFIER=/^[A-Za-z_][A-Za-z0-9_]*$/;export const assertSqlIdentifier=(e,t="identifier")=>{if("string"!=typeof e||!IDENTIFIER.test(e))throw new Error(`[@webority/mobile-core] Invalid SQL ${t} ${JSON.stringify(e)}. Only letters, digits and underscores are allowed, and it must not start with a digit. Pass values as bound parameters instead of building them into the name.`);return e};const quoteIdentifier=(e,t="identifier")=>`"${assertSqlIdentifier(e,t)}"`,escapeIdentifier=e=>`"${e.replace(/"/g,'""')}"`,COLUMN_DEFINITION=/^[A-Za-z0-9_ ,.()'"+*/=<>|%:$-]+$/,assertColumnDefinition=(e,t)=>{const r="string"==typeof e?e.trim():"";if(0===r.length||!COLUMN_DEFINITION.test(r)||r.includes("--"))throw new Error(`[@webority/mobile-core] Invalid column definition for "${t}": ${JSON.stringify(e)}. A definition is raw SQL such as 'INTEGER NOT NULL DEFAULT 0' and may not contain a statement separator or a comment.`);return r};export const toSqliteValue=e=>void 0===e?null:"boolean"==typeof e?e?1:0:e instanceof Date?e.toISOString():e;export const fromSqliteBoolean=e=>{if("boolean"==typeof e)return e;if("number"==typeof e)return 0!==e;if("string"==typeof e){const t=e.trim().toLowerCase();return"1"===t||"true"===t}return!1};export const whereIn=(e,t)=>{const r=quoteIdentifier(e,"column name");return 0===t.length?{sql:"1 = 0",params:[]}:{sql:`${r} IN (${t.map(()=>"?").join(", ")})`,params:t.map(toSqliteValue)}};const isRawWhere=e=>"string"==typeof e.sql&&Object.keys(e).every(e=>"sql"===e||"params"===e),buildWhere=e=>{if(!e)return{clause:"",params:[]};if(isRawWhere(e)){const t=e.sql.trim();return 0===t.length?{clause:"",params:[]}:{clause:` WHERE ${t}`,params:[...e.params??[]]}}const t=Object.entries(e);if(0===t.length)return{clause:"",params:[]};const r=[],n=[];for(const[e,i]of t){const t=quoteIdentifier(e,"column name"),o=toSqliteValue(i);null===o?r.push(`${t} IS NULL`):(r.push(`${t} = ?`),n.push(o))}return{clause:` WHERE ${r.join(" AND ")}`,params:n}},buildOrderBy=e=>{if(void 0===e)return"";const t=e.split(",").map(e=>e.trim()).filter(e=>e.length>0);if(0===t.length)return"";return` ORDER BY ${t.map(t=>{const[r,n,...i]=t.split(/\s+/);if(i.length>0)throw new Error(`[@webority/mobile-core] Invalid orderBy term ${JSON.stringify(t)}. Expected a column name optionally followed by ASC or DESC.`);const o=quoteIdentifier(r,"orderBy column");if(void 0===n)return o;const a=n.toUpperCase();if("ASC"!==a&&"DESC"!==a)throw new Error(`[@webority/mobile-core] Invalid sort direction ${JSON.stringify(n)} in orderBy ${JSON.stringify(e)}. Expected ASC or DESC.`);return`${o} ${a}`}).join(", ")}`},assertNonNegativeInteger=(e,t)=>{if(!Number.isInteger(e)||e<0)throw new Error(`[@webority/mobile-core] Invalid ${t} ${JSON.stringify(e)}. Expected a non-negative integer.`);return e},hashString=e=>{let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return`${t.toString(16).padStart(8,"0")}-${e.length.toString(16)}`},migrationChecksum=e=>{if("function"==typeof e.up)return hashString("fn");const t=Array.isArray(e.up)?e.up.join("\n"):e.up;return hashString(t)};export const DEFAULT_PRAGMAS={journal_mode:"WAL",synchronous:"NORMAL",foreign_keys:"ON",busy_timeout:5e3};const PRAGMA_VALUE=/^[A-Za-z0-9_-]+$/,renderPragmaValue=(e,t)=>{if("number"==typeof t){if(!Number.isFinite(t))throw new Error(`[@webority/mobile-core] Invalid value for PRAGMA ${e}: ${t}.`);return String(t)}if(!PRAGMA_VALUE.test(t))throw new Error(`[@webority/mobile-core] Invalid value ${JSON.stringify(t)} for PRAGMA ${e}. PRAGMA values cannot be bound, so only letters, digits, underscores and hyphens are accepted.`);return t},rowFieldMissing=(e,t)=>new Error(`[${e}] row has no ${t}`),parseCount=e=>{if("number"!=typeof e.cnt)throw rowFieldMissing("sqlite","cnt");return e.cnt},parseUserVersion=e=>{if("number"!=typeof e.user_version)throw rowFieldMissing("sqlite","user_version");return e.user_version},parseForeignKeys=e=>{if("number"!=typeof e.foreign_keys)throw rowFieldMissing("sqlite","foreign_keys");return e.foreign_keys},parseTableName=e=>{if("string"!=typeof e.name)throw rowFieldMissing("sqlite","name");return e.name},parseLedgerRow=e=>{if("number"!=typeof e.version)throw rowFieldMissing("sqlite","version");if("string"!=typeof e.checksum)throw rowFieldMissing("sqlite","checksum");return{version:e.version,checksum:e.checksum}},queriesOver=e=>{const rowsOf=async(t,r,n)=>(await e(t,r)).rows.map((e,t)=>{if(!isRecord(e))throw new Error(`[sqlite] row ${t} is not an object`);return n?n(e):e});return{execute:e,select:function select(e,t,r){return rowsOf(e,t,r)},selectOne:async function selectOne(e,t,r){const[n]=await rowsOf(e,t,r);return n??null}}},createDb=(e,t)=>{let r=Promise.resolve();const exclusive=e=>{const t=r.then(e);return r=Promise.allSettled([t]),t},run=async(e,r)=>{try{return await t.execute(e,r)}catch(t){throw Logger.error(`[@webority/mobile-core] SQLite execute failed: ${e}`,t),t}},n=queriesOver(run),{execute:i,select:o,selectOne:a}=queriesOver((e,t)=>exclusive(()=>run(e,t))),runTransaction=async e=>{let r=!0;const n=queriesOver((e,t)=>r?run(e,t):Promise.reject(new Error("[@webority/mobile-core] A transaction handle was used after its transaction ended. Use the database itself outside transaction().")));try{let r;await t.execute("BEGIN");try{r=await e(n)}catch(e){try{await t.execute("ROLLBACK")}catch(e){Logger.error("[@webority/mobile-core] SQLite ROLLBACK failed",e)}throw e}try{await t.execute("COMMIT")}catch(e){try{await t.execute("ROLLBACK")}catch(e){Logger.error("[@webority/mobile-core] SQLite ROLLBACK after a failed COMMIT failed",e)}throw e}return r}finally{r=!1}},transaction=e=>exclusive(()=>runTransaction(e)),insertSql=(e,t)=>{const r=quoteIdentifier(e,"table name"),n=Object.entries(t);if(0===n.length)throw new Error(`[@webority/mobile-core] Cannot insert an empty row into ${e}. Pass at least one column.`);const i=n.map(([e])=>quoteIdentifier(e,"column name")),o=n.map(()=>"?");return{sql:`INSERT INTO ${r} (${i.join(", ")}) VALUES (${o.join(", ")})`,params:n.map(([,e])=>toSqliteValue(e))}},findRows=async(e,t,r,n)=>{const i=quoteIdentifier(e,"table name"),a=buildWhere(t),s=[...a.params];let c=`SELECT * FROM ${i}${a.clause}${buildOrderBy(r?.orderBy)}`;return void 0!==r?.limit?(assertNonNegativeInteger(r.limit,"limit"),c+=" LIMIT ?",s.push(r.limit)):void 0!==r?.offset&&(c+=" LIMIT -1"),void 0!==r?.offset&&(assertNonNegativeInteger(r.offset,"offset"),c+=" OFFSET ?",s.push(r.offset)),n?o(c,s,n):o(c,s)};const ensureLedger=async()=>{await i(`CREATE TABLE IF NOT EXISTS ${escapeIdentifier(MIGRATIONS_TABLE)} (version INTEGER PRIMARY KEY, name TEXT, applied_at TEXT NOT NULL, checksum TEXT NOT NULL)`)},s=`INSERT OR REPLACE INTO ${escapeIdentifier(MIGRATIONS_TABLE)} (version, name, applied_at, checksum) VALUES (?, ?, ?, ?)`,wipe=()=>exclusive(async()=>{const e=1===await n.selectOne("PRAGMA foreign_keys",void 0,parseForeignKeys);await run("PRAGMA foreign_keys = OFF");try{await runTransaction(async e=>{const t=await e.select("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name <> ?",[MIGRATIONS_TABLE],parseTableName);for(const r of t)await e.execute(`DELETE FROM ${escapeIdentifier(r)}`)})}finally{await run("PRAGMA foreign_keys = "+(e?"ON":"OFF"))}}),migrate=async(t,r)=>{const n=new Set;for(const r of t){if(n.has(r.version))throw new Error(`[@webority/mobile-core] Duplicate migration version ${r.version} for database "${e}".`);n.add(r.version)}let i=await a("PRAGMA user_version",void 0,parseUserVersion)??0;if(t.length>0&&!r?.allowDowngrade){const r=t.reduce((e,t)=>Math.max(e,t.version),0);if(i>r)throw new Error(`[@webority/mobile-core] Database "${e}" is at schema version ${i}, which is newer than the highest migration supplied (${r}). This build would run old code against a newer schema. Ship the missing migrations, or pass { allowDowngrade: true } if this build is known to be compatible.`)}await ensureLedger();const c=await o(`SELECT version, checksum FROM ${escapeIdentifier(MIGRATIONS_TABLE)}`,void 0,parseLedgerRow),l=new Map(c.map(e=>[e.version,e.checksum]));for(const r of t){if(r.version>i)continue;const t=l.get(r.version);if(void 0===t)continue;const n=migrationChecksum(r);if(t!==n)throw new Error(`[@webority/mobile-core] Migration ${r.version} has changed since it was applied to database "${e}" (recorded ${t}, now ${n}). A released migration must never be edited; add a new one instead.`)}const u=t.filter(e=>e.version>i).sort((e,t)=>e.version-t.version);for(const e of u){const t=migrationChecksum(e);await transaction(async r=>{if("function"==typeof e.up)await e.up(r);else{const t=Array.isArray(e.up)?e.up:[e.up];for(const e of t)await r.execute(e)}await r.execute(s,[e.version,e.name??null,(new Date).toISOString(),t]),await r.execute(`PRAGMA user_version = ${e.version}`)}),i=e.version}return i};return{name:e,execute:i,select:o,selectOne:a,transaction:transaction,insert:async(e,t)=>{const{sql:r,params:n}=insertSql(e,t);return(await i(r,n)).insertId},insertMany:async(e,t)=>{if(0===t.length)return 0;const r=t.map(t=>insertSql(e,t));return await transaction(async e=>{for(const t of r)await e.execute(t.sql,t.params)}),t.length},update:async(e,t,r)=>{const n=quoteIdentifier(e,"table name"),o=Object.entries(t);if(0===o.length)throw new Error(`[@webority/mobile-core] Cannot update ${e} with no values. Pass at least one column to set.`);const a=o.map(([e])=>`${quoteIdentifier(e,"column name")} = ?`),s=o.map(([,e])=>toSqliteValue(e)),c=buildWhere(r);return(await i(`UPDATE ${n} SET ${a.join(", ")}${c.clause}`,[...s,...c.params])).rowsAffected},remove:async(e,t)=>{const r=quoteIdentifier(e,"table name"),n=buildWhere(t);return(await i(`DELETE FROM ${r}${n.clause}`,n.params)).rowsAffected},upsert:async(e,t,r)=>{if(0===r.length)throw new Error(`[@webority/mobile-core] upsert on ${e} needs at least one conflict column; without one SQLite has no key to match an existing row on.`);const{sql:n,params:o}=insertSql(e,t),a=new Set(r),s=r.map(e=>quoteIdentifier(e,"column name")),c=Object.keys(t).filter(e=>!a.has(e)).map(e=>{const t=quoteIdentifier(e,"column name");return`${t} = excluded.${t}`}),l=c.length>0?`DO UPDATE SET ${c.join(", ")}`:"DO NOTHING";await i(`${n} ON CONFLICT (${s.join(", ")}) ${l}`,o)},findAll:function findAll(e,t,r,n){return findRows(e,t,r,n)},findOne:async function findOne(e,t,r){const[n]=await findRows(e,t,{limit:1},r);return n??null},count:async(e,t)=>{const r=quoteIdentifier(e,"table name"),n=buildWhere(t);return await a(`SELECT COUNT(*) AS cnt FROM ${r}${n.clause}`,n.params,parseCount)??0},tableExists:async e=>{assertSqlIdentifier(e,"table name");return null!==await a("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?",[e])},createTable:async(e,t,r)=>{const n=quoteIdentifier(e,"table name"),o=Object.entries(t);if(0===o.length)throw new Error(`[@webority/mobile-core] Cannot create table ${e} with no columns.`);const a=o.map(([e,t])=>`${quoteIdentifier(e,"column name")} ${assertColumnDefinition(t,e)}`),s=!1===r?.ifNotExists?"":"IF NOT EXISTS ";await i(`CREATE TABLE ${s}${n} (${a.join(", ")})`)},dropTable:async(e,t)=>{const r=quoteIdentifier(e,"table name"),n=!1===t?.ifExists?"":"IF EXISTS ";await i(`DROP TABLE ${n}${r}`)},wipe:wipe,reset:async e=>(await wipe(),await ensureLedger(),await transaction(async e=>{await e.execute(`DELETE FROM ${escapeIdentifier(MIGRATIONS_TABLE)}`),await e.execute("PRAGMA user_version = 0")}),migrate(e)),migrate:migrate,baseline:async(e,t)=>{assertNonNegativeInteger(e,"baseline version"),await ensureLedger();const r=(new Date).toISOString();await transaction(async n=>{for(const i of t??[])i.version>e||await n.execute(s,[i.version,i.name??null,r,migrationChecksum(i)]);await n.execute(`PRAGMA user_version = ${e}`)})},close:()=>exclusive(()=>t.close())}};export const openDatabase=async(e,t)=>{const r=requireBackend("open"),n=await r.open(e,t?{location:t.location}:void 0),i=createDb(e,n);if(!1!==t?.pragmas){const e={...DEFAULT_PRAGMAS,...t?.pragmas??{}};for(const[t,r]of Object.entries(e))assertSqlIdentifier(t,"PRAGMA name"),await i.execute(`PRAGMA ${t} = ${renderPragmaValue(t,r)}`)}return i};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import KvStore from"expo-sqlite/kv-store";import{Logger}from"../logger/index.js";let backend=null;const resolveBackend=()=>backend??
|
|
1
|
+
"use strict";import KvStore from"expo-sqlite/kv-store";import{Logger}from"../logger/index.js";let backend=null;const defaultBackend=KvStore,resolveBackend=()=>backend??defaultBackend;export const isStorageAvailable=()=>null!==resolveBackend();const requireBackend=e=>{const t=resolveBackend();if(!t){const t=new Error(`[Storage] no storage backend available; cannot ${e}.`);throw Logger.error(t.message),t}return t};export const setStorageImplementation=e=>{backend=e};const safeJsonParse=e=>{if(null==e)return null;try{return JSON.parse(e)}catch(e){return Logger.warn("[Storage] Failed to parse JSON value, returning null",e),null}},getItem=async e=>{try{return await requireBackend("getItem").getItem(e)}catch(t){return Logger.error(`[Storage] getItem failed for key "${e}"`,t),null}},setItem=async(e,t)=>{try{return await requireBackend("setItem").setItem(e,t),!0}catch(t){return Logger.error(`[Storage] setItem failed for key "${e}"`,t),!1}},removeItem=async e=>{try{return await requireBackend("removeItem").removeItem(e),!0}catch(t){return Logger.error(`[Storage] removeItem failed for key "${e}"`,t),!1}},getJson=async(e,t)=>{const r=safeJsonParse(await getItem(e));return null===r?null:t(r)},setJson=async(e,t)=>{try{return await setItem(e,JSON.stringify(t))}catch(t){return Logger.error(`[Storage] setJson failed for key "${e}"`,t),!1}},multiGet=async e=>{try{const t=requireBackend("multiGet");if(t.getMany)return await t.getMany([...e]);if(!t.multiGet){const r={};return await Promise.all(e.map(async e=>{r[e]=await t.getItem(e)})),r}const r=await t.multiGet([...e]),a={};for(const[e,t]of r)a[e]=t;return a}catch(e){return Logger.error("[Storage] multiGet failed",e),{}}},multiSet=async e=>{try{const t=requireBackend("multiSet");if(t.setMany)return await t.setMany(e),!0;const r=Object.entries(e);return t.multiSet?(await t.multiSet(r),!0):(await Promise.all(r.map(([e,r])=>t.setItem(e,r))),!0)}catch(e){return Logger.error("[Storage] multiSet failed",e),!1}},multiRemove=async e=>{try{const t=requireBackend("multiRemove");return t.removeMany?(await t.removeMany([...e]),!0):t.multiRemove?(await t.multiRemove([...e]),!0):(await Promise.all(e.map(e=>t.removeItem(e))),!0)}catch(e){return Logger.error("[Storage] multiRemove failed",e),!1}},clear=async()=>{try{const e=requireBackend("clear");return e.clear?(await e.clear(),!0):(Logger.warn("[Storage] backend does not support clear()"),!1)}catch(e){return Logger.error("[Storage] clear failed",e),!1}},getAllKeys=async()=>{try{const e=requireBackend("getAllKeys");if(!e.getAllKeys)return[];return[...await e.getAllKeys()]}catch(e){return Logger.error("[Storage] getAllKeys failed",e),[]}};export const Storage={getItem:getItem,setItem:setItem,removeItem:removeItem,getJson:getJson,setJson:setJson,multiGet:multiGet,multiSet:multiSet,multiRemove:multiRemove,clear:clear,getAllKeys:getAllKeys};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";export{};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{useSyncExternalStore}from"react";import{AppState,Platform}from"react-native";import{getConfigValue}from"../config/index.js";import{ENVIRONMENT_APP_ID_SUFFIX}from"../config/appIdentity.js";import{Logger}from"../logger/index.js";import{Storage}from"../storage/index.js";const PREFIX="[@webority/mobile-core] OTA updates:",REPORTED_KEY="@webority/ota/last-reported-update-id";export const OTA_LAST_LAUNCH_KEY="@webority/ota/last-launch";const ENV_IDENTITY_SUFFIXES=Object.values(ENVIRONMENT_APP_ID_SUFFIX).filter(e=>""!==e);export const DEFAULT_MIN_CHECK_INTERVAL_MS=9e5;const EVENT_TIMEOUT_MS=1e4;let resolved,override=null;export const setOtaUpdatesImplementation=e=>{override=e};const resolveUpdates=()=>{if(__DEV__)return null;if(override)return override;if(void 0!==resolved)return resolved;try{
|
|
1
|
+
"use strict";import{useSyncExternalStore}from"react";import{AppState,Platform}from"react-native";import{getConfigValue}from"../config/index.js";import{ENVIRONMENT_APP_ID_SUFFIX}from"../config/appIdentity.js";import{Logger}from"../logger/index.js";import{Storage}from"../storage/index.js";const PREFIX="[@webority/mobile-core] OTA updates:",REPORTED_KEY="@webority/ota/last-reported-update-id";export const OTA_LAST_LAUNCH_KEY="@webority/ota/last-launch";const ENV_IDENTITY_SUFFIXES=Object.values(ENVIRONMENT_APP_ID_SUFFIX).filter(e=>""!==e);export const DEFAULT_MIN_CHECK_INTERVAL_MS=9e5;const EVENT_TIMEOUT_MS=1e4;let resolved,override=null;export const setOtaUpdatesImplementation=e=>{override=e};const resolveUpdates=()=>{if(__DEV__)return null;if(override)return override;if(void 0!==resolved)return resolved;try{const e=require("expo-updates");resolved=e}catch{resolved=null}return resolved},INITIAL_STATE={status:"unavailable",runningUpdateId:null,error:null,lastCheckedAt:null};let state=INITIAL_STATE;const subscribers=new Set,setState=e=>{state={...state,...e};for(const e of subscribers)e()};let config=null,stateSubscription=null,appStateSubscription=null,checking=null,lastCheckStartedAt=0,lastReportedError=null;const messageOf=e=>e instanceof Error?e.message:String(e);export const normalizeAppIdentity=e=>{const t=String(e??"").trim().toLowerCase(),r=ENV_IDENTITY_SUFFIXES.find(e=>t.endsWith(e));return r?t.slice(0,-r.length):t};const ownIdentity=()=>config?.appIdentifier??getConfigValue("appId",null)??null,identityMismatch=e=>{const t=e?.extra?.webority?.appIdentifier;if(!t)return null;const r=ownIdentity();return r&&normalizeAppIdentity(t)===normalizeAppIdentity(r)?null:`identity mismatch: the update is for '${t}' but this app is '${r??"unset"}'`},postEvent=async(e,t,r)=>{const a=config?.serverUrl;if(!a||!e)return;const n=new AbortController,s=setTimeout(()=>n.abort(),1e4);try{await fetch(`${a.replace(/\/+$/,"")}/ota/updates/${encodeURIComponent(e)}/events`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:t,platform:Platform.OS,runtimeVersion:resolveUpdates()?.runtimeVersion??null,message:r}),signal:n.signal})}catch(e){Logger.info(`${PREFIX} the ${t} event was not reported: ${messageOf(e)}`)}finally{clearTimeout(s)}},reportError=(e,t)=>{setState({status:"error",error:t});const r=`${e??""}|${t}`;r!==lastReportedError&&(lastReportedError=r,Logger.error(`${PREFIX} ${t}`),postEvent(e,"error",t))},recordLaunch=async e=>{const t={updateId:e.updateId,channel:e.channel??null,runtimeVersion:e.runtimeVersion,isEmbeddedLaunch:e.isEmbeddedLaunch,isEmergencyLaunch:e.isEmergencyLaunch??!1,emergencyLaunchReason:e.emergencyLaunchReason??null,launchedAtUtc:(new Date).toISOString()};await Storage.setItem(OTA_LAST_LAUNCH_KEY,JSON.stringify(t))||Logger.error(`${PREFIX} the launch record was not saved`)},reportRunningUpdate=async e=>{if(await recordLaunch(e),e.isEmbeddedLaunch||!e.updateId)return;const t=identityMismatch(e.manifest);t?reportError(e.updateId,t):await Storage.getItem(REPORTED_KEY)!==e.updateId&&(await postEvent(e.updateId,"success"),await Storage.setItem(REPORTED_KEY,e.updateId),Logger.info(`${PREFIX} running update ${e.updateId}`))},onStateChange=e=>{const t=e.downloadError??e.checkError;if(t){const r=e.latestManifest?.id??resolveUpdates()?.updateId;return void reportError(r,t.message)}e.isChecking?setState({status:"checking"}):e.isDownloading?setState({status:"downloading"}):e.isUpdatePending&&setState({status:"ready",error:null})};export const checkForOtaUpdate=()=>{const e=resolveUpdates();if(!config||!e?.isEnabled)return Promise.resolve("unavailable");if(checking)return checking;lastCheckStartedAt=Date.now();return checking=(async()=>{try{setState({status:"checking"});const t=await e.checkForUpdateAsync();if(t.isAvailable){const e=identityMismatch(t.manifest);if(e)return reportError(t.manifest?.id,e),"error"}return t.isAvailable||t.isRollBackToEmbedded?(setState({status:"downloading"}),await e.fetchUpdateAsync(),setState({status:"ready",error:null}),"ready"):(setState({status:"ready"===state.status?"ready":"idle",error:null}),state.status)}catch(t){return reportError(e.updateId,messageOf(t)),"error"}finally{setState({lastCheckedAt:Date.now()}),checking=null}})(),checking};const onAppStateChange=e=>{if("active"!==e||!1===config?.checkOnForeground)return;const t=config?.minCheckIntervalMs??9e5;Date.now()-lastCheckStartedAt<t||checkForOtaUpdate()};export const initOtaUpdates=e=>{const t=null===config;if(config=e,!t)return;const r=resolveUpdates();if(!r?.isEnabled)return void setState({status:"unavailable"});setState({status:"idle",runningUpdateId:r.isEmbeddedLaunch?null:r.updateId}),reportRunningUpdate(r).catch(e=>{Logger.info(`${PREFIX} start-up report failed: ${messageOf(e)}`)}),"function"==typeof r.addUpdatesStateChangeListener&&(stateSubscription=r.addUpdatesStateChangeListener(e=>onStateChange(e.context))),appStateSubscription=AppState.addEventListener("change",onAppStateChange);"ON_LOAD"===r.checkAutomatically||"WIFI_ONLY"===r.checkAutomatically||checkForOtaUpdate()};export const applyOtaUpdate=async()=>{const e=resolveUpdates();e?.isEnabled&&"ready"===state.status&&await e.reloadAsync()};export const stopOtaUpdates=()=>{stateSubscription?.remove(),appStateSubscription?.remove(),stateSubscription=null,appStateSubscription=null,config=null,checking=null,lastCheckStartedAt=0,lastReportedError=null,resolved=void 0,setState(INITIAL_STATE)};const subscribe=e=>(subscribers.add(e),()=>{subscribers.delete(e)}),getSnapshot=()=>state;export const useOtaUpdates=()=>({...useSyncExternalStore(subscribe,getSnapshot,getSnapshot),check:checkForOtaUpdate,apply:applyOtaUpdate});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const CHUNK=8192;export const encodeBase64=t=>{const r=new Uint8Array(t);let e="";for(let t=0;t<r.length;t+=8192)e+=String.fromCharCode
|
|
1
|
+
"use strict";const CHUNK=8192;export const encodeBase64=t=>{const r=new Uint8Array(t);let e="";for(let t=0;t<r.length;t+=8192)e+=String.fromCharCode(...r.subarray(t,t+8192));return btoa(e)};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";export function isOneOf(e,r){return e.some(e=>e===r)}export function hasKey(e,r){return Object.hasOwn(e,r)}export function isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}export function keysOf(e){return Object.keys(e).filter(r=>hasKey(e,r))}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{File}from"expo-file-system";import{ImageManipulator}from"expo-image-manipulator";import{Logger}from"../logger/index.js";export class ImageUnreadableError extends Error{constructor(e,t){super(`Image is unreadable (${t}): ${e||"<empty uri>"}`),this.name="ImageUnreadableError",this.uri=e}}const release=e=>{try{e?.release?.()}catch{}},expoBackend={stat:async e=>{const t=new File(e);return t.exists?null==t.size?null:{exists:!0,size:t.size}:{exists:!1,size:0}},remove:async e=>{new File(e).delete()},open:async e=>{const t=ImageManipulator.manipulate(e);let i;try{i=await t.renderAsync()}finally{release(t)}return{width:i.width,height:i.height,encode:async({width:e,height:t,quality:a,format:r})=>{const n=ImageManipulator.manipulate(i);let o=null;try{void 0===e&&void 0===t||n.resize({width:e??null,height:t??null}),o=await n.renderAsync();const i=await o.saveAsync({compress:a,format:r});return{uri:i.uri,width:i.width,height:i.height}}finally{release(o),release(n)}},close:()=>release(i)}}};let backend=null;export const setImageCompressorImplementation=e=>{backend=e};const resolveBackend=()=>backend??expoBackend,EIGHT_MB=8388608,THREE_MB=3145728;export const qualityForFileSize=e=>null==e?.7:e>8388608?.6:e>3145728?.7:.8;const DEFAULT_MAX_SIZE=1500,DEFAULT_MIN_QUALITY=.4,QUALITY_STEP=.1,SIZE_STEP=.75,MIN_SIDE=320,FORMAT={jpg:{encode:"jpeg",mimeType:"image/jpeg"},png:{encode:"png",mimeType:"image/png"},webp:{encode:"webp",mimeType:"image/webp"}},MIME_BY_EXTENSION={jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",webp:"image/webp",gif:"image/gif",heic:"image/heic",heif:"image/heif",bmp:"image/bmp",tif:"image/tiff",tiff:"image/tiff"},lastSegment=e=>{const t=e.split(/[?#]/)[0]??"";return decodeURIComponentSafe(t.slice(t.lastIndexOf("/")+1))},decodeURIComponentSafe=e=>{try{return decodeURIComponent(e)}catch{return e}},extensionOf=e=>{const t=e.lastIndexOf(".");return t>0?e.slice(t+1).toLowerCase():""},withoutExtension=e=>{const t=e.lastIndexOf(".");return t>0?e.slice(0,t):e},baseNameFor=(e,t)=>withoutExtension(t?.trim()||lastSegment(e))||"image",round1=e=>Math.round(10*e)/10,safeStat=async(e,t)=>{try{return await e.stat(t)}catch{return null}},safeRemove=async(e,t)=>{try{await e.remove(t)}catch{}},renderWithin=async(e,t,i,a,r)=>{const n=Math.max(t.width,t.height)>i?t.width>=t.height?{width:i}:{height:i}:{},o=await t.encode({...n,quality:a,format:r}),s=await safeStat(e,o.uri);if(s&&(!s.exists||0===s.size))throw await safeRemove(e,o.uri),new ImageUnreadableError(o.uri,"the encoder wrote an empty file");return{...o,size:s?.size??null}},originalResult=(e,t,i,a)=>{const r=extensionOf(lastSegment(e))||"jpg",n=MIME_BY_EXTENSION[r]??"image/jpeg",o=`${i}.${r}`;return{uri:e,width:a?.width??null,height:a?.height??null,size:t,mimeType:n,extension:r,fileName:o,compressed:!1,quality:null,part:{uri:e,name:o,type:n}}};export const compressImage=async(e,t={})=>{if(!e)throw new ImageUnreadableError(e,"no uri");const i=resolveBackend(),{maxSize:a=DEFAULT_MAX_SIZE,output:r="jpg",maxBytes:n,minQuality:o=DEFAULT_MIN_QUALITY,name:s}=t,l=FORMAT[r]??FORMAT.jpg,m=baseNameFor(e,s),g=await safeStat(i,e);if(g&&!g.exists)throw new ImageUnreadableError(e,"the file does not exist");if(g&&0===g.size)throw new ImageUnreadableError(e,"the file is empty");const h=g?.size??t.fileSize??null;let c
|
|
1
|
+
"use strict";import{File}from"expo-file-system";import{ImageManipulator,SaveFormat}from"expo-image-manipulator";import{Logger}from"../logger/index.js";export class ImageUnreadableError extends Error{constructor(e,t){super(`Image is unreadable (${t}): ${e||"<empty uri>"}`),this.name="ImageUnreadableError",this.uri=e}}const release=e=>{try{e?.release?.()}catch{}},SAVE_FORMAT={jpeg:SaveFormat.JPEG,png:SaveFormat.PNG,webp:SaveFormat.WEBP},expoBackend={stat:async e=>{const t=new File(e);return t.exists?null==t.size?null:{exists:!0,size:t.size}:{exists:!1,size:0}},remove:async e=>{new File(e).delete()},open:async e=>{const t=ImageManipulator.manipulate(e);let i;try{i=await t.renderAsync()}finally{release(t)}return{width:i.width,height:i.height,encode:async({width:e,height:t,quality:a,format:r})=>{const n=ImageManipulator.manipulate(i);let o=null;try{void 0===e&&void 0===t||n.resize({width:e??null,height:t??null}),o=await n.renderAsync();const i=await o.saveAsync({compress:a,format:SAVE_FORMAT[r]});return{uri:i.uri,width:i.width,height:i.height}}finally{release(o),release(n)}},close:()=>release(i)}}};let backend=null;export const setImageCompressorImplementation=e=>{backend=e};const resolveBackend=()=>backend??expoBackend,EIGHT_MB=8388608,THREE_MB=3145728;export const qualityForFileSize=e=>null==e?.7:e>8388608?.6:e>3145728?.7:.8;const DEFAULT_MAX_SIZE=1500,DEFAULT_MIN_QUALITY=.4,QUALITY_STEP=.1,SIZE_STEP=.75,MIN_SIDE=320,FORMAT={jpg:{encode:"jpeg",mimeType:"image/jpeg"},png:{encode:"png",mimeType:"image/png"},webp:{encode:"webp",mimeType:"image/webp"}},MIME_BY_EXTENSION={jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",webp:"image/webp",gif:"image/gif",heic:"image/heic",heif:"image/heif",bmp:"image/bmp",tif:"image/tiff",tiff:"image/tiff"},lastSegment=e=>{const t=e.split(/[?#]/)[0]??"";return decodeURIComponentSafe(t.slice(t.lastIndexOf("/")+1))},decodeURIComponentSafe=e=>{try{return decodeURIComponent(e)}catch{return e}},extensionOf=e=>{const t=e.lastIndexOf(".");return t>0?e.slice(t+1).toLowerCase():""},withoutExtension=e=>{const t=e.lastIndexOf(".");return t>0?e.slice(0,t):e},baseNameFor=(e,t)=>withoutExtension(t?.trim()||lastSegment(e))||"image",round1=e=>Math.round(10*e)/10,safeStat=async(e,t)=>{try{return await e.stat(t)}catch{return null}},safeRemove=async(e,t)=>{try{await e.remove(t)}catch{}},renderWithin=async(e,t,i,a,r)=>{const n=Math.max(t.width,t.height)>i?t.width>=t.height?{width:i}:{height:i}:{},o=await t.encode({...n,quality:a,format:r}),s=await safeStat(e,o.uri);if(s&&(!s.exists||0===s.size))throw await safeRemove(e,o.uri),new ImageUnreadableError(o.uri,"the encoder wrote an empty file");return{...o,size:s?.size??null}},originalResult=(e,t,i,a)=>{const r=extensionOf(lastSegment(e))||"jpg",n=MIME_BY_EXTENSION[r]??"image/jpeg",o=`${i}.${r}`;return{uri:e,width:a?.width??null,height:a?.height??null,size:t,mimeType:n,extension:r,fileName:o,compressed:!1,quality:null,part:{uri:e,name:o,type:n}}};export const compressImage=async(e,t={})=>{if(!e)throw new ImageUnreadableError(e,"no uri");const i=resolveBackend(),{maxSize:a=DEFAULT_MAX_SIZE,output:r="jpg",maxBytes:n,minQuality:o=DEFAULT_MIN_QUALITY,name:s}=t,l=FORMAT[r]??FORMAT.jpg,m=baseNameFor(e,s),g=await safeStat(i,e);if(g&&!g.exists)throw new ImageUnreadableError(e,"the file does not exist");if(g&&0===g.size)throw new ImageUnreadableError(e,"the file is empty");const h=g?.size??t.fileSize??null;let p,c;try{p=await i.open(e)}catch(t){throw Logger.error("[imageCompression] could not decode the image",t),new ImageUnreadableError(e,"the photo could not be decoded")}try{let e=t.quality??qualityForFileSize(h),s=a;if(c=await renderWithin(i,p,s,e,l.encode),void 0!==n)for(;null!==c.size&&c.size>n;){if("png"!==r&&round1(e-.1)>=o)e=round1(e-.1);else{const e=Math.max(c.width,c.height);if(e<=320)break;s=Math.max(320,Math.floor(.75*e))}const t=await renderWithin(i,p,s,e,l.encode);await safeRemove(i,c.uri),c=t}const g=`${m}.${r}`;return{uri:c.uri,width:c.width,height:c.height,size:c.size,mimeType:l.mimeType,extension:r,fileName:g,compressed:!0,quality:"png"===r?null:e,part:{uri:c.uri,name:g,type:l.mimeType}}}catch(t){if(c&&await safeRemove(i,c.uri),t instanceof ImageUnreadableError)throw t;Logger.error("[imageCompression] encoding failed; retrying once as jpeg at quality 0.7",t);try{const e=await renderWithin(i,p,a,.7,"jpeg"),t=`${m}.jpg`;return{uri:e.uri,width:e.width,height:e.height,size:e.size,mimeType:"image/jpeg",extension:"jpg",fileName:t,compressed:!0,quality:.7,part:{uri:e.uri,name:t,type:"image/jpeg"}}}catch(t){if(t instanceof ImageUnreadableError)throw t;Logger.error("[imageCompression] jpeg retry failed",t);if(Math.max(p.width,p.height)<=a&&(void 0===n||null!==h&&h<=n))return originalResult(e,h,m,{width:p.width,height:p.height});throw new ImageUnreadableError(e,"the photo could not be prepared for upload")}}finally{p.close()}};
|
|
@@ -33,7 +33,7 @@ export interface AccountStampedConfig {
|
|
|
33
33
|
set: (name: string, value: string) => unknown;
|
|
34
34
|
};
|
|
35
35
|
/** The workspace the request was made in; `null` when it named none, unset until first sent. */
|
|
36
|
-
_accountId?: string | null;
|
|
36
|
+
_accountId?: string | null | undefined;
|
|
37
37
|
}
|
|
38
38
|
/**
|
|
39
39
|
* Stamps Account-Id once, on the first send, and records it on the config. A request must
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type OperationEntry, type OperationShape } from "@webority/api-contract/call";
|
|
2
|
+
import type { AxiosInstance, AxiosRequestConfig } from "axios";
|
|
3
|
+
export type ContractCaller<TOperations extends {
|
|
4
|
+
readonly [K in keyof TOperations]: OperationShape;
|
|
5
|
+
}> = <TId extends keyof TOperations & string>(id: TId, request: TOperations[TId]["request"], config?: Pick<AxiosRequestConfig, "signal" | "timeout">) => Promise<TOperations[TId]["response"]>;
|
|
6
|
+
export declare const createContractCaller: <TOperations extends { readonly [K in keyof TOperations]: OperationShape; }>(client: AxiosInstance, operations: { readonly [K in keyof TOperations & string]: OperationEntry; }) => ContractCaller<TOperations>;
|
|
7
|
+
//# sourceMappingURL=contractCaller.d.ts.map
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
export interface FetchRetryPolicy {
|
|
2
2
|
/** Resends after the first attempt; 0 turns retrying off. */
|
|
3
|
-
retries?: number;
|
|
3
|
+
retries?: number | undefined;
|
|
4
4
|
/** `attempt` is 1-based: 1 is the first resend. */
|
|
5
|
-
retryDelayMs?: (attempt: number) => number;
|
|
5
|
+
retryDelayMs?: ((attempt: number) => number) | undefined;
|
|
6
6
|
/** Treat this request as a read: it changes nothing on the server, so it is resent like a GET. */
|
|
7
|
-
sideEffectFree?: boolean;
|
|
7
|
+
sideEffectFree?: boolean | undefined;
|
|
8
8
|
}
|
|
9
9
|
/**
|
|
10
10
|
* A write is resent only under the shared rule in retry.ts. A rejection that is not a TypeError is thrown at once, not retried.
|
|
@@ -1,15 +1,21 @@
|
|
|
1
1
|
import { type AxiosError, type AxiosInstance, type GenericAbortSignal } from "axios";
|
|
2
2
|
export interface RetryPolicy {
|
|
3
|
-
retries?: number;
|
|
3
|
+
retries?: number | undefined;
|
|
4
4
|
/** `attempt` is 1-based: 1 is the first retry, not the original request. */
|
|
5
|
-
retryDelayMs?: (attempt: number) => number;
|
|
6
|
-
shouldRetry?: (error: AxiosError) => boolean;
|
|
7
|
-
onRetry?: (attempt: number, error: AxiosError) => void;
|
|
5
|
+
retryDelayMs?: ((attempt: number) => number) | undefined;
|
|
6
|
+
shouldRetry?: ((error: AxiosError) => boolean) | undefined;
|
|
7
|
+
onRetry?: ((attempt: number, error: AxiosError) => void) | undefined;
|
|
8
8
|
}
|
|
9
9
|
declare module "axios" {
|
|
10
10
|
interface AxiosRequestConfig {
|
|
11
11
|
/** `false` opts a single request out of retrying; an object overrides the client policy. */
|
|
12
|
-
retry?: boolean | RetryPolicy;
|
|
12
|
+
retry?: boolean | RetryPolicy | undefined;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
declare module "axios" {
|
|
16
|
+
interface InternalAxiosRequestConfig {
|
|
17
|
+
__retryAttempt?: number | undefined;
|
|
18
|
+
__retryStartedAt?: number | undefined;
|
|
13
19
|
}
|
|
14
20
|
}
|
|
15
21
|
/**
|
|
@@ -22,7 +22,8 @@ export interface RefreshableStore {
|
|
|
22
22
|
export declare class SessionEndedError extends Error {
|
|
23
23
|
constructor(message: string);
|
|
24
24
|
}
|
|
25
|
-
|
|
25
|
+
/** Pass `null` to detach the store, as a test's teardown does. */
|
|
26
|
+
export declare const injectStore: (nextStore: RefreshableStore | null) => void;
|
|
26
27
|
export declare const injectUserAuth: (options: UserAuthOptions) => void;
|
|
27
28
|
/**
|
|
28
29
|
* Clear any in-flight token refresh and reject everything queued behind it.
|
|
@@ -11,6 +11,17 @@ export { injectStore, injectUserAuth, resetRefreshState, SESSION_EXPIRED_CODE, S
|
|
|
11
11
|
export declare class RequestOfflineError extends Error {
|
|
12
12
|
constructor(message?: string);
|
|
13
13
|
}
|
|
14
|
+
declare module "axios" {
|
|
15
|
+
interface InternalAxiosRequestConfig {
|
|
16
|
+
_retry?: boolean | undefined;
|
|
17
|
+
/** Replayed once because the session changed while it was in flight; never replayed for that again. */
|
|
18
|
+
_replayedWithCurrentToken?: boolean | undefined;
|
|
19
|
+
/** Closes the session-replacement window a `replacesSession` request opened. */
|
|
20
|
+
_endReplacement?: (() => void) | undefined;
|
|
21
|
+
_accountId?: string | null | undefined;
|
|
22
|
+
_transformGuarded?: boolean | undefined;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
14
25
|
declare const userClient: AxiosInstance;
|
|
15
26
|
export default userClient;
|
|
16
27
|
//# sourceMappingURL=userClient.d.ts.map
|
|
@@ -18,11 +18,11 @@ interface WorkspaceChangedResponse {
|
|
|
18
18
|
export declare class WorkspaceChangedError extends Error {
|
|
19
19
|
readonly code = "workspace_changed";
|
|
20
20
|
readonly response: WorkspaceChangedResponse;
|
|
21
|
-
readonly config?: InternalAxiosRequestConfig;
|
|
21
|
+
readonly config?: InternalAxiosRequestConfig | undefined;
|
|
22
22
|
readonly cause?: unknown;
|
|
23
23
|
constructor(message?: string, options?: {
|
|
24
|
-
response?: WorkspaceChangedResponse;
|
|
25
|
-
config?: InternalAxiosRequestConfig;
|
|
24
|
+
response?: WorkspaceChangedResponse | undefined;
|
|
25
|
+
config?: InternalAxiosRequestConfig | undefined;
|
|
26
26
|
cause?: unknown;
|
|
27
27
|
});
|
|
28
28
|
}
|
|
@@ -32,6 +32,6 @@ export declare function authenticateBiometric(reason: string): Promise<AppLockRe
|
|
|
32
32
|
*/
|
|
33
33
|
export declare function useAppLock({ active, policy }: {
|
|
34
34
|
active: boolean;
|
|
35
|
-
policy?: Partial<AppLockPolicy
|
|
35
|
+
policy?: Partial<AppLockPolicy> | undefined;
|
|
36
36
|
}): AppLockState;
|
|
37
37
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -7,7 +7,7 @@ export declare const mimeTypeFromFileName: (fileName: string | null | undefined)
|
|
|
7
7
|
export interface AttachmentRequest {
|
|
8
8
|
url: string;
|
|
9
9
|
fileName: string;
|
|
10
|
-
mimeType?: string | null;
|
|
10
|
+
mimeType?: string | null | undefined;
|
|
11
11
|
}
|
|
12
12
|
/**
|
|
13
13
|
* Fetches a file through the signed-in client into the app's cache, where a viewer or a save reads it. Answers with
|
|
@@ -16,7 +16,7 @@ export interface AttachmentRequest {
|
|
|
16
16
|
export declare const fetchAttachment: ({ url, fileName, mimeType }: AttachmentRequest) => Promise<DownloadResult>;
|
|
17
17
|
export interface PreviewAttachment {
|
|
18
18
|
path: string;
|
|
19
|
-
mimeType?: string;
|
|
19
|
+
mimeType?: string | undefined;
|
|
20
20
|
folder: string;
|
|
21
21
|
}
|
|
22
22
|
/**
|
|
@@ -26,12 +26,12 @@ export interface PreviewAttachment {
|
|
|
26
26
|
*/
|
|
27
27
|
export declare const fetchPreviewAttachment: ({ cacheId, version, url, fileName, mimeType, }: AttachmentRequest & {
|
|
28
28
|
cacheId: string;
|
|
29
|
-
version?: string | null;
|
|
29
|
+
version?: string | null | undefined;
|
|
30
30
|
}) => Promise<PreviewAttachment | DownloadResult>;
|
|
31
31
|
export type PreviewKind = "image" | "pdf";
|
|
32
32
|
/** What the app can show itself, from a content type or a file name: "image", "pdf", or null for anything else. */
|
|
33
33
|
export declare const previewKind: (file: {
|
|
34
|
-
contentType?: string | null;
|
|
35
|
-
name?: string | null;
|
|
34
|
+
contentType?: string | null | undefined;
|
|
35
|
+
name?: string | null | undefined;
|
|
36
36
|
}) => PreviewKind | null;
|
|
37
37
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -51,7 +51,7 @@ export interface LegacyTokenKeys {
|
|
|
51
51
|
accessToken: string;
|
|
52
52
|
refreshToken: string;
|
|
53
53
|
/** The old key of the signed-in user's profile snapshot, if the app kept one. */
|
|
54
|
-
sessionUser?: string;
|
|
54
|
+
sessionUser?: string | undefined;
|
|
55
55
|
}
|
|
56
56
|
/**
|
|
57
57
|
* The expiry given to a migrated refresh token whose expiry the old store never kept and which
|
|
@@ -93,13 +93,13 @@ interface SecureCredentials {
|
|
|
93
93
|
}
|
|
94
94
|
interface KeychainLike {
|
|
95
95
|
setGenericPassword: (username: string, password: string, options?: {
|
|
96
|
-
service?: string;
|
|
96
|
+
service?: string | undefined;
|
|
97
97
|
}) => Promise<unknown>;
|
|
98
98
|
getGenericPassword: (options?: {
|
|
99
|
-
service?: string;
|
|
99
|
+
service?: string | undefined;
|
|
100
100
|
}) => Promise<SecureCredentials | false>;
|
|
101
101
|
resetGenericPassword: (options?: {
|
|
102
|
-
service?: string;
|
|
102
|
+
service?: string | undefined;
|
|
103
103
|
}) => Promise<unknown>;
|
|
104
104
|
}
|
|
105
105
|
/**
|
|
@@ -113,7 +113,9 @@ export declare const setKeychainImplementation: (impl: KeychainLike | null) => v
|
|
|
113
113
|
*/
|
|
114
114
|
export declare const storeToken: (key: string, token: string, expiry: string) => Promise<void>;
|
|
115
115
|
/**
|
|
116
|
-
* Retrieve token and check if expired.
|
|
116
|
+
* Retrieve token and check if expired. Rejects when the store cannot be read
|
|
117
|
+
* (other than an invalidated key, which is cleared and read as no token), and
|
|
118
|
+
* when a legacy session move fails.
|
|
117
119
|
*/
|
|
118
120
|
export declare const getToken: (key: string) => Promise<StoredToken | null>;
|
|
119
121
|
/**
|
|
@@ -130,7 +132,7 @@ export declare const storeSessionUser: <T>(user: T) => Promise<void>;
|
|
|
130
132
|
* The stored user, or null. An unreadable snapshot is removed and reported,
|
|
131
133
|
* but does not end the session: it is a cache the next profile fetch refills.
|
|
132
134
|
*/
|
|
133
|
-
export declare const getSessionUser: <T>() => Promise<T | null>;
|
|
135
|
+
export declare const getSessionUser: <T>(parse: (value: unknown) => T) => Promise<T | null>;
|
|
134
136
|
export declare const removeSessionUser: () => Promise<void>;
|
|
135
137
|
/** Set by `initUserAuth({ legacyKeys })`; `null` turns the migration off. */
|
|
136
138
|
export declare const setLegacyTokenKeys: (keys: LegacyTokenKeys | null) => void;
|
|
@@ -3,20 +3,23 @@
|
|
|
3
3
|
* `sub`, `exp`, `iat`, `nbf` follow RFC 7519 conventions.
|
|
4
4
|
*/
|
|
5
5
|
export interface JwtClaims {
|
|
6
|
-
sub?: string;
|
|
7
|
-
exp?: number;
|
|
8
|
-
iat?: number;
|
|
9
|
-
nbf?: number;
|
|
10
|
-
iss?: string;
|
|
11
|
-
aud?: string | string[];
|
|
6
|
+
sub?: string | undefined;
|
|
7
|
+
exp?: number | undefined;
|
|
8
|
+
iat?: number | undefined;
|
|
9
|
+
nbf?: number | undefined;
|
|
10
|
+
iss?: string | undefined;
|
|
11
|
+
aud?: string | string[] | undefined;
|
|
12
12
|
[key: string]: unknown;
|
|
13
13
|
}
|
|
14
14
|
/**
|
|
15
15
|
* Decode a JWT's payload claims. Does **not** verify the signature.
|
|
16
16
|
*
|
|
17
|
-
*
|
|
17
|
+
* Without `parse`, returns the claims. With `parse`, returns what `parse` builds from them; a throw from `parse` propagates.
|
|
18
|
+
*
|
|
19
|
+
* @returns claims (or the value `parse` returns) on success, `null` if the token is malformed or a standard claim has the wrong type.
|
|
18
20
|
*/
|
|
19
|
-
export declare
|
|
21
|
+
export declare function decodeJWT(token: string): JwtClaims | null;
|
|
22
|
+
export declare function decodeJWT<T>(token: string, parse: (claims: JwtClaims) => T): T | null;
|
|
20
23
|
/**
|
|
21
24
|
* Returns true when the token is expired (or unparseable / missing `exp`).
|
|
22
25
|
*
|
|
@@ -18,31 +18,37 @@ export interface ParsedLink {
|
|
|
18
18
|
export interface DeepLinkRoute {
|
|
19
19
|
/** A path pattern with `:param` segments (`order/:id`), or a RegExp on `path`. */
|
|
20
20
|
match: string | RegExp;
|
|
21
|
-
requiresAuth?: boolean;
|
|
21
|
+
requiresAuth?: boolean | undefined;
|
|
22
22
|
handler: (link: ParsedLink, params: Record<string, string>) => void;
|
|
23
23
|
}
|
|
24
24
|
export interface DeepLinkConfig {
|
|
25
25
|
routes: DeepLinkRoute[];
|
|
26
26
|
/** Navigator readiness. Links arriving before this is true are queued. */
|
|
27
|
-
isReady?: () => boolean;
|
|
28
|
-
isAuthenticated?: () => boolean;
|
|
27
|
+
isReady?: (() => boolean) | undefined;
|
|
28
|
+
isAuthenticated?: (() => boolean) | undefined;
|
|
29
29
|
/** Called when an auth-gated link is stashed; the app sends the user to login. */
|
|
30
|
-
onUnauthenticated?: (link: ParsedLink) => void;
|
|
31
|
-
onUnmatched?: (link: ParsedLink) => void;
|
|
30
|
+
onUnauthenticated?: ((link: ParsedLink) => void) | undefined;
|
|
31
|
+
onUnmatched?: ((link: ParsedLink) => void) | undefined;
|
|
32
32
|
}
|
|
33
33
|
/**
|
|
34
34
|
* Parse a deep-link URL. Returns null for anything that is not a usable URL so
|
|
35
35
|
* a hostile or truncated link can never throw on the native event path.
|
|
36
36
|
*/
|
|
37
37
|
export declare const parseDeepLink: (url: string) => ParsedLink | null;
|
|
38
|
+
declare const flushPending: () => void;
|
|
39
|
+
declare const configure: (next: DeepLinkConfig) => void;
|
|
40
|
+
declare const handleUrl: (url: string) => void;
|
|
41
|
+
declare const start: () => Promise<void>;
|
|
42
|
+
declare const stop: () => void;
|
|
43
|
+
declare const setReady: (ready: boolean) => void;
|
|
38
44
|
export declare const DeepLink: {
|
|
39
|
-
configure:
|
|
40
|
-
start:
|
|
41
|
-
stop:
|
|
42
|
-
handleUrl:
|
|
43
|
-
setReady:
|
|
45
|
+
configure: typeof configure;
|
|
46
|
+
start: typeof start;
|
|
47
|
+
stop: typeof stop;
|
|
48
|
+
handleUrl: typeof handleUrl;
|
|
49
|
+
setReady: typeof setReady;
|
|
44
50
|
/** Replay the stashed link, once. Call after a successful login. */
|
|
45
|
-
replayPending:
|
|
51
|
+
replayPending: typeof flushPending;
|
|
46
52
|
getPending: () => ParsedLink | null;
|
|
47
53
|
};
|
|
48
54
|
/**
|
|
@@ -51,4 +57,5 @@ export declare const DeepLink: {
|
|
|
51
57
|
* not tear down and re-subscribe the native listener.
|
|
52
58
|
*/
|
|
53
59
|
export declare const useDeepLink: (deepLinkConfig: DeepLinkConfig) => void;
|
|
60
|
+
export {};
|
|
54
61
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -12,8 +12,8 @@ interface ExpoFileLike {
|
|
|
12
12
|
readonly exists: boolean;
|
|
13
13
|
readonly size: number;
|
|
14
14
|
create: (options?: {
|
|
15
|
-
intermediates?: boolean;
|
|
16
|
-
overwrite?: boolean;
|
|
15
|
+
intermediates?: boolean | undefined;
|
|
16
|
+
overwrite?: boolean | undefined;
|
|
17
17
|
}) => void;
|
|
18
18
|
write: (content: Uint8Array) => Promise<void>;
|
|
19
19
|
delete: () => void;
|
|
@@ -21,8 +21,8 @@ interface ExpoFileLike {
|
|
|
21
21
|
interface ExpoDirectoryLike {
|
|
22
22
|
readonly uri: string;
|
|
23
23
|
create: (options?: {
|
|
24
|
-
intermediates?: boolean;
|
|
25
|
-
idempotent?: boolean;
|
|
24
|
+
intermediates?: boolean | undefined;
|
|
25
|
+
idempotent?: boolean | undefined;
|
|
26
26
|
}) => void;
|
|
27
27
|
}
|
|
28
28
|
export interface ExpoFileSystemModuleLike {
|
|
@@ -18,6 +18,10 @@ export interface FileSystemLike {
|
|
|
18
18
|
unlink: (path: string) => Promise<void>;
|
|
19
19
|
mkdir: (path: string) => Promise<void>;
|
|
20
20
|
}
|
|
21
|
+
/**
|
|
22
|
+
* Built by downloadFile and handed to the client, never written by an app: its optional keys are absent rather
|
|
23
|
+
* than undefined, so an axios instance (whose config refuses an explicit undefined) satisfies DownloadHttpClient.
|
|
24
|
+
*/
|
|
21
25
|
export interface DownloadHttpRequestConfig {
|
|
22
26
|
headers?: Record<string, string>;
|
|
23
27
|
responseType: "arraybuffer";
|
|
@@ -25,7 +29,7 @@ export interface DownloadHttpRequestConfig {
|
|
|
25
29
|
signal?: AbortSignal;
|
|
26
30
|
onDownloadProgress?: (event: {
|
|
27
31
|
loaded: number;
|
|
28
|
-
total?: number;
|
|
32
|
+
total?: number | undefined;
|
|
29
33
|
}) => void;
|
|
30
34
|
}
|
|
31
35
|
/**
|
|
@@ -36,8 +40,8 @@ export interface DownloadHttpRequestConfig {
|
|
|
36
40
|
* mobile-support's client is, so no axios type leaks into the declarations.
|
|
37
41
|
*/
|
|
38
42
|
export interface DownloadHttpClient {
|
|
39
|
-
get
|
|
40
|
-
data:
|
|
43
|
+
get(url: string, config?: DownloadHttpRequestConfig): Promise<{
|
|
44
|
+
data: unknown;
|
|
41
45
|
}>;
|
|
42
46
|
}
|
|
43
47
|
export type DownloadDestination = "documents" | "cache" | "downloads";
|
|
@@ -45,25 +49,25 @@ export interface DownloadOptions {
|
|
|
45
49
|
/** Sends the request: `userClient` for a signed-in download, `publicClient` for an open one. */
|
|
46
50
|
client: DownloadHttpClient;
|
|
47
51
|
url: string;
|
|
48
|
-
fileName?: string;
|
|
49
|
-
destination?: DownloadDestination;
|
|
52
|
+
fileName?: string | undefined;
|
|
53
|
+
destination?: DownloadDestination | undefined;
|
|
50
54
|
/** Sent with the request, beside whatever the client adds itself. */
|
|
51
|
-
headers?: Record<string, string
|
|
52
|
-
mimeType?: string;
|
|
53
|
-
onProgress?: (received: number, total: number, fraction: number) => void;
|
|
54
|
-
overwrite?: boolean;
|
|
55
|
-
signal?: AbortSignal;
|
|
55
|
+
headers?: Record<string, string> | undefined;
|
|
56
|
+
mimeType?: string | undefined;
|
|
57
|
+
onProgress?: ((received: number, total: number, fraction: number) => void) | undefined;
|
|
58
|
+
overwrite?: boolean | undefined;
|
|
59
|
+
signal?: AbortSignal | undefined;
|
|
56
60
|
}
|
|
57
61
|
export interface DownloadResult {
|
|
58
62
|
path: string;
|
|
59
63
|
bytes: number;
|
|
60
|
-
mimeType?: string;
|
|
64
|
+
mimeType?: string | undefined;
|
|
61
65
|
fromCache: boolean;
|
|
62
66
|
}
|
|
63
67
|
export type DownloadErrorCode = "unsupported" | "permission-denied" | "network" | "http-error" | "write-failed" | "aborted" | "empty-file";
|
|
64
68
|
export declare class DownloadError extends Error {
|
|
65
69
|
readonly code: DownloadErrorCode;
|
|
66
|
-
readonly status?: number;
|
|
70
|
+
readonly status?: number | undefined;
|
|
67
71
|
constructor(code: DownloadErrorCode, message: string, status?: number);
|
|
68
72
|
}
|
|
69
73
|
/**
|