@webority/mobile-core 0.146.1 → 0.147.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/commonjs/api/idempotencyKey.js +1 -1
- package/lib/commonjs/auth/jwt.js +1 -1
- package/lib/commonjs/errors/extractApiError.js +1 -1
- package/lib/commonjs/formatters/formatConfig.js +1 -1
- package/lib/commonjs/india/aadhaar.js +1 -1
- package/lib/commonjs/india/financialYear.js +1 -1
- package/lib/commonjs/sqlite/index.js +1 -1
- package/lib/module/api/idempotencyKey.js +1 -1
- package/lib/module/auth/jwt.js +1 -1
- package/lib/module/errors/extractApiError.js +1 -1
- package/lib/module/formatters/formatConfig.js +1 -1
- package/lib/module/india/aadhaar.js +1 -1
- package/lib/module/india/financialYear.js +1 -1
- package/lib/module/sqlite/index.js +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.newIdempotencyKey=void 0;const cryptoApi=()=>globalThis.crypto,randomBytes16=()=>{const e=new Uint8Array(16),t=cryptoApi();if("function"==typeof t?.getRandomValues)t.getRandomValues(e);else for(let t=0;t<e.length;t+=1)e[t]=Math.floor(256*Math.random());return e},formatUuid=e=>{const t=Array.from(e,e=>e.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20,32)}`},newIdempotencyKey=()=>{const e=cryptoApi();if("function"==typeof e?.randomUUID)return e.randomUUID();const t=randomBytes16()
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.newIdempotencyKey=void 0;const cryptoApi=()=>globalThis.crypto,randomBytes16=()=>{const e=new Uint8Array(16),t=cryptoApi();if("function"==typeof t?.getRandomValues)t.getRandomValues(e);else for(let t=0;t<e.length;t+=1)e[t]=Math.floor(256*Math.random());return e},formatUuid=e=>{const t=Array.from(e,e=>e.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20,32)}`},newIdempotencyKey=()=>{const e=cryptoApi();if("function"==typeof e?.randomUUID)return e.randomUUID();const t=Array.from(randomBytes16(),(e,t)=>6===t?15&e|64:8===t?63&e|128:e);return formatUuid(t)};exports.newIdempotencyKey=newIdempotencyKey;
|
package/lib/commonjs/auth/jwt.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.isJWTExpired=exports.getJWTExpiry=exports.decodeJWT=void 0;var _index=require("../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=
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.isJWTExpired=exports.getJWTExpiry=exports.decodeJWT=void 0;var _index=require("../logger/index.js");const base64UrlToBase64=e=>(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),BASE64_ALPHABET="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",sextetAt=(e,t)=>{const r=e.charAt(t);return""===r?-1:BASE64_ALPHABET.indexOf(r)},decodeBase64Fallback=e=>{let t="";for(let r=0;r<e.length;r+=4){const o=sextetAt(e,r),n=sextetAt(e,r+1),a=sextetAt(e,r+2),d=sextetAt(e,r+3),s=Math.max(o,0)<<18|Math.max(n,0)<<12|Math.max(a,0)<<6|Math.max(d,0);t+=String.fromCharCode(s>>16&255),-1!==a&&(t+=String.fromCharCode(s>>8&255)),-1!==d&&(t+=String.fromCharCode(255&s))}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}},decodeJWT=e=>{if(!e||"string"!=typeof e)return null;const t=e.split("."),r=3===t.length?t[1]:void 0;if(void 0===r)return _index.Logger.warn("[jwt] decodeJWT: token is not a valid JWT (expected 3 segments)"),null;try{const e=utf8FromBinary(decodeBase64(base64UrlToBase64(r)));return JSON.parse(e)}catch(e){return _index.Logger.warn("[jwt] decodeJWT failed to parse payload",e),null}};exports.decodeJWT=decodeJWT;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};exports.isJWTExpired=isJWTExpired;const getJWTExpiry=e=>{const t=decodeJWT(e);return t&&"number"==typeof t.exp?new Date(1e3*t.exp):null};exports.getJWTExpiry=getJWTExpiry;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.UNREACHABLE_MESSAGE=exports.UNEXPECTED_MESSAGE=exports.TIMEOUT_MESSAGE=exports.TIMEOUT_CODE=exports.SERVER_FAILURE_MESSAGE=exports.REQUEST_CANCELED_CODE=exports.OFFLINE_MESSAGE=exports.OFFLINE_CODE=exports.NETWORK_CODE=exports.CONTRACT_ERROR_CODE=void 0,exports.apiErrorMessage=apiErrorMessage,exports.extractApiError=extractApiError,exports.toFieldPath=exports.isNoResponse=exports.isApiError=void 0;const SERVER_FAILURE_MESSAGE=exports.SERVER_FAILURE_MESSAGE="Something went wrong on our side. Please try again in a moment.",OFFLINE_MESSAGE=exports.OFFLINE_MESSAGE="You appear to be offline. Check your connection and try again.",TIMEOUT_MESSAGE=exports.TIMEOUT_MESSAGE="That took too long to respond. Check your connection and try again.",UNEXPECTED_MESSAGE=exports.UNEXPECTED_MESSAGE="Something went wrong. Please try again.",UNREACHABLE_MESSAGE=exports.UNREACHABLE_MESSAGE="We couldn't reach the server. Check your connection and try again.",REQUEST_CANCELED_CODE=exports.REQUEST_CANCELED_CODE="request_canceled",CONTRACT_ERROR_CODE=exports.CONTRACT_ERROR_CODE="contract_error",TIMEOUT_CODE=exports.TIMEOUT_CODE="timeout",NETWORK_CODE=exports.NETWORK_CODE="network",OFFLINE_CODE=exports.OFFLINE_CODE="offline",INTERNAL_ERROR_CODE="internal_error",MAX_MESSAGE_LENGTH=300,requestFailedMessage=e=>`Request failed (${e})`,FLEET_DEFAULT_REFUSALS={401:{code:"unauthorized",sentence:"Please sign in to continue."},403:{code:"forbidden",sentence:"You do not have access to this."}},isDict=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),nonEmptyString=e=>"string"==typeof e&&e.trim().length>0?e:null,fleetDefaultRefusalSentence=(e,t)=>{const r=FLEET_DEFAULT_REFUSALS[e];if(void 0===r||null===t||t.code!==r.code)return null;const s=nonEmptyString(t.detail);return null===s||s===r.sentence?r.sentence:null},looksLikeDiagnostics=e=>e.length>300||/^\s*</.test(e)||e.includes("\n at ")||/(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},toFieldPath=e=>e.replace(/^\$\.?/,"").split(".").map(e=>e.charAt(0).toLowerCase()+e.slice(1)).join(".");exports.toFieldPath=toFieldPath;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 s=toFieldPath(t);""===s?e.form??=r:s in e.fields||(e.fields[s]=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,s]of Object.entries(e)){const e=firstMessage(s);null!==e&&addError(t,r,e)}return t},isApiError=e=>isDict(e)&&"string"==typeof e.message&&"number"==typeof e.status&&"boolean"==typeof e.offline&&isDict(e.fieldErrors);exports.isApiError=isApiError;const build=e=>({code:null,fieldErrors:{},status:0,offline:!1,traceId:null,diagnostic:null,...e}),requestTraceId=e=>{const t=isDict(e.config)?e.config.headers:void 0;if(!isDict(t))return null;const r="function"==typeof t.get?t.get("traceparent"):t.traceparent??t.Traceparent,s="string"==typeof r?/^00-([0-9a-f]{32})-[0-9a-f]{16}-[0-9a-f]{2}$/.exec(r):null;return s
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.UNREACHABLE_MESSAGE=exports.UNEXPECTED_MESSAGE=exports.TIMEOUT_MESSAGE=exports.TIMEOUT_CODE=exports.SERVER_FAILURE_MESSAGE=exports.REQUEST_CANCELED_CODE=exports.OFFLINE_MESSAGE=exports.OFFLINE_CODE=exports.NETWORK_CODE=exports.CONTRACT_ERROR_CODE=void 0,exports.apiErrorMessage=apiErrorMessage,exports.extractApiError=extractApiError,exports.toFieldPath=exports.isNoResponse=exports.isApiError=void 0;const SERVER_FAILURE_MESSAGE=exports.SERVER_FAILURE_MESSAGE="Something went wrong on our side. Please try again in a moment.",OFFLINE_MESSAGE=exports.OFFLINE_MESSAGE="You appear to be offline. Check your connection and try again.",TIMEOUT_MESSAGE=exports.TIMEOUT_MESSAGE="That took too long to respond. Check your connection and try again.",UNEXPECTED_MESSAGE=exports.UNEXPECTED_MESSAGE="Something went wrong. Please try again.",UNREACHABLE_MESSAGE=exports.UNREACHABLE_MESSAGE="We couldn't reach the server. Check your connection and try again.",REQUEST_CANCELED_CODE=exports.REQUEST_CANCELED_CODE="request_canceled",CONTRACT_ERROR_CODE=exports.CONTRACT_ERROR_CODE="contract_error",TIMEOUT_CODE=exports.TIMEOUT_CODE="timeout",NETWORK_CODE=exports.NETWORK_CODE="network",OFFLINE_CODE=exports.OFFLINE_CODE="offline",INTERNAL_ERROR_CODE="internal_error",MAX_MESSAGE_LENGTH=300,requestFailedMessage=e=>`Request failed (${e})`,FLEET_DEFAULT_REFUSALS={401:{code:"unauthorized",sentence:"Please sign in to continue."},403:{code:"forbidden",sentence:"You do not have access to this."}},isDict=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),nonEmptyString=e=>"string"==typeof e&&e.trim().length>0?e:null,fleetDefaultRefusalSentence=(e,t)=>{const r=FLEET_DEFAULT_REFUSALS[e];if(void 0===r||null===t||t.code!==r.code)return null;const s=nonEmptyString(t.detail);return null===s||s===r.sentence?r.sentence:null},looksLikeDiagnostics=e=>e.length>300||/^\s*</.test(e)||e.includes("\n at ")||/(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},toFieldPath=e=>e.replace(/^\$\.?/,"").split(".").map(e=>e.charAt(0).toLowerCase()+e.slice(1)).join(".");exports.toFieldPath=toFieldPath;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 s=toFieldPath(t);""===s?e.form??=r:s in e.fields||(e.fields[s]=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,s]of Object.entries(e)){const e=firstMessage(s);null!==e&&addError(t,r,e)}return t},isApiError=e=>isDict(e)&&"string"==typeof e.message&&"number"==typeof e.status&&"boolean"==typeof e.offline&&isDict(e.fieldErrors);exports.isApiError=isApiError;const build=e=>({code:null,fieldErrors:{},status:0,offline:!1,traceId:null,diagnostic:null,...e}),requestTraceId=e=>{const t=isDict(e.config)?e.config.headers:void 0;if(!isDict(t))return null;const r="function"==typeof t.get?t.get("traceparent"):t.traceparent??t.Traceparent,s="string"==typeof r?/^00-([0-9a-f]{32})-[0-9a-f]{16}-[0-9a-f]{2}$/.exec(r):null;return s?.[1]??null},fromNoResponse=e=>{const t=nonEmptyString(e.code),r=nonEmptyString(e.name),s=nonEmptyString(e.message),E=requestTraceId(e);return build("CanceledError"===r||"ERR_CANCELED"===t?{code:REQUEST_CANCELED_CODE,message:UNEXPECTED_MESSAGE,traceId:E,diagnostic:s}:"ECONNABORTED"===t||"ETIMEDOUT"===t?{code:TIMEOUT_CODE,message:TIMEOUT_MESSAGE,offline:!0,traceId:E,diagnostic:s}:"RequestOfflineError"===r?{code:OFFLINE_CODE,message:OFFLINE_MESSAGE,offline:!0,traceId:E,diagnostic:s}:"ERR_NETWORK"===t||"Network Error"===s||"Network request failed"===s?{code:NETWORK_CODE,message:UNREACHABLE_MESSAGE,offline:!0,traceId:E,diagnostic:s}:{message:UNEXPECTED_MESSAGE,traceId:E,diagnostic:s})};function extractApiError(e){if(isApiError(e))return e;if("string"==typeof e)return build({message:userSafe(e)??UNEXPECTED_MESSAGE,diagnostic:e||null});if(!isDict(e))return build({message:UNEXPECTED_MESSAGE,diagnostic:null==e?null:String(e)});if(!0===e.isContractError)return build({code:CONTRACT_ERROR_CODE,message:userSafe(e.message)??UNEXPECTED_MESSAGE,diagnostic: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,s=t?t.data:e.body;if(0===r&&null==s)return fromNoResponse(e);const E=isDict(s)?s:null,{fields:n,form:o}=readErrors(E?.errors),i=nonEmptyString(E?.code),a=nonEmptyString(E?.traceId)??requestTraceId(e),l=nonEmptyString(E?.detail)??nonEmptyString(E?.title)??nonEmptyString(s)??nonEmptyString(e.message);let c;if(r>=500){c=(null!==i&&i!==INTERNAL_ERROR_CODE?userSafe(E?.detail):null)??SERVER_FAILURE_MESSAGE}else c=fleetDefaultRefusalSentence(r,E)??userSafe(Object.values(n)[0])??userSafe(o)??userSafe(E?.detail)??userSafe(E?.title)??userSafe(s)??(r?requestFailedMessage(r):UNEXPECTED_MESSAGE);return build({code:i,message:c,fieldErrors:n,status:r,traceId:a,diagnostic:l})}const isNoResponse=e=>extractApiError(e).offline;function apiErrorMessage(e,t){const r=extractApiError(e);if(r.offline||null!==t&&!t)return r.message;return r.message===SERVER_FAILURE_MESSAGE||r.code===REQUEST_CANCELED_CODE||r.message===UNEXPECTED_MESSAGE||r.message===requestFailedMessage(r.status)?t??null:r.message}exports.isNoResponse=isNoResponse;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.styledNumber=exports.numberSeparators=exports.isFormatterConfigured=exports.groupingForLocale=exports.getFormatterConfig=exports.configuredLocale=exports.configureFormatters=void 0;const DEFAULTS={zone:"IST",locale:"en-IN",empty:"-"},SEPARATORS={PointWithCommaGroups:{decimal:".",group:","},CommaWithPointGroups:{decimal:",",group:"."},CommaWithSpaceGroups:{decimal:",",group:" "},PointWithSpaceGroups:{decimal:".",group:" "}},DATE_ORDERS=["DayMonthNameYear","DayMonthYear","MonthDayYear","YearMonthDay"];let current={...DEFAULTS},configured=new Set;const configureFormatters=
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.styledNumber=exports.numberSeparators=exports.isFormatterConfigured=exports.groupingForLocale=exports.getFormatterConfig=exports.configuredLocale=exports.configureFormatters=void 0;const DEFAULTS={zone:"IST",locale:"en-IN",empty:"-"},SEPARATORS={PointWithCommaGroups:{decimal:".",group:","},CommaWithPointGroups:{decimal:",",group:"."},CommaWithSpaceGroups:{decimal:",",group:" "},PointWithSpaceGroups:{decimal:".",group:" "}},DATE_ORDERS=["DayMonthNameYear","DayMonthYear","MonthDayYear","YearMonthDay"];let current={...DEFAULTS},configured=new Set;const configureFormatters=r=>{if(void 0===r)return current={...DEFAULTS},void(configured=new Set);if(void 0!==r.numberStyle&&!Object.hasOwn(SEPARATORS,r.numberStyle))throw new RangeError(`Unknown number style "${r.numberStyle}"; expected one of ${Object.keys(SEPARATORS).join(", ")}.`);if(void 0!==r.dateOrder&&!DATE_ORDERS.includes(r.dateOrder))throw new RangeError(`Unknown date order "${r.dateOrder}"; expected one of ${DATE_ORDERS.join(", ")}.`);for(const e of Object.keys(r)){const t=r[e];void 0!==t&&(current={...current,[e]:t},configured.add(e))}};exports.configureFormatters=configureFormatters;const getFormatterConfig=()=>({...current});exports.getFormatterConfig=getFormatterConfig;const isFormatterConfigured=r=>configured.has(r);exports.isFormatterConfigured=isFormatterConfigured;const configuredLocale=()=>configured.has("locale")?current.locale:null;exports.configuredLocale=configuredLocale;const groupingForLocale=r=>/-IN(?:-|$)/i.test(r)?"indian":"international";exports.groupingForLocale=groupingForLocale;const numberSeparators=()=>void 0===current.numberStyle?null:SEPARATORS[current.numberStyle];exports.numberSeparators=numberSeparators;const localeMarks=new Map,digitsOf=r=>{const e=new Intl.NumberFormat(r,{useGrouping:!1}),t=new Set;for(let r=0;r<=9;r++)t.add(e.format(r));return t},separatorRuns=(r,e)=>{const t=[];let o=[],n=!1;for(const a of r)e.has(a)?(o.length>0&&(t.push(o),o=[]),n=!0):n&&o.push(a);return t},marksOf=r=>{const e=localeMarks.get(r);if(void 0!==e)return e;const t=digitsOf(r),o=new Intl.NumberFormat(r,{useGrouping:!0,minimumFractionDigits:1,maximumFractionDigits:1}).format(11111.5),n=separatorRuns(Array.from(o),t),a={digits:t,decimal:n.at(-1)??null,group:n.length>=2?n.at(0)??null:null};return localeMarks.set(r,a),a},isDigitAt=(r,e,t)=>{const o=e>=0?r.at(e):void 0;return void 0!==o&&t.has(o)},swapMarks=(r,e,t)=>{const o=Array.from(r);let n="",a=0;for(;a<o.length;){const r=t.find(({mark:r})=>isDigitAt(o,a-1,e)&&r.every((r,e)=>o[a+e]===r)&&isDigitAt(o,a+r.length,e));void 0===r?(n+=o[a],a+=1):(n+=r.to,a+=r.mark.length)}return n},styledNumber=(r,e)=>{const t=numberSeparators();if(null===t)return r.format(e);const{digits:o,decimal:n,group:a}=marksOf(r.resolvedOptions().locale),s=[];return null!==n&&s.push({mark:n,to:t.decimal}),null!==a&&s.push({mark:a,to:t.group}),swapMarks(r.format(e),o,s)};exports.styledNumber=styledNumber;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.normalizeAadhaar=exports.maskAadhaar=exports.isAadhaar=exports.aadhaarLastFour=void 0;var _text=require("./text.js");const RE_AADHAAR=/^[2-9][0-9]{11}$/,VERHOEFF_D=[[0,1,2,3,4,5,6,7,8,9],[1,2,3,4,0,6,7,8,9,5],[2,3,4,0,1,7,8,9,5,6],[3,4,0,1,2,8,9,5,6,7],[4,0,1,2,3,9,5,6,7,8],[5,9,8,7,6,0,4,3,2,1],[6,5,9,8,7,1,0,4,3,2],[7,6,5,9,8,2,1,0,4,3],[8,7,6,5,9,3,2,1,0,4],[9,8,7,6,5,4,3,2,1,0]],VERHOEFF_P=[[0,1,2,3,4,5,6,7,8,9],[1,5,7,6,2,8,3,0,9,4],[5,8,0,3,7,9,6,1,4,2],[8,9,1,6,0,4,3,5,2,7],[9,4,5,3,1,2,6,8,7,0],[4,2,8,6,5,7,3,9,0,1],[2,7,9,3,8,0,6,4,1,5],[7,0,4,6,9,1,3,2,5,8]],isVerhoeffValid=a=>{let r=0;for(let
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.normalizeAadhaar=exports.maskAadhaar=exports.isAadhaar=exports.aadhaarLastFour=void 0;var _text=require("./text.js");const RE_AADHAAR=/^[2-9][0-9]{11}$/,VERHOEFF_D=[[0,1,2,3,4,5,6,7,8,9],[1,2,3,4,0,6,7,8,9,5],[2,3,4,0,1,7,8,9,5,6],[3,4,0,1,2,8,9,5,6,7],[4,0,1,2,3,9,5,6,7,8],[5,9,8,7,6,0,4,3,2,1],[6,5,9,8,7,1,0,4,3,2],[7,6,5,9,8,2,1,0,4,3],[8,7,6,5,9,3,2,1,0,4],[9,8,7,6,5,4,3,2,1,0]],VERHOEFF_P=[[0,1,2,3,4,5,6,7,8,9],[1,5,7,6,2,8,3,0,9,4],[5,8,0,3,7,9,6,1,4,2],[8,9,1,6,0,4,3,5,2,7],[9,4,5,3,1,2,6,8,7,0],[4,2,8,6,5,7,3,9,0,1],[2,7,9,3,8,0,6,4,1,5],[7,0,4,6,9,1,3,2,5,8]],isVerhoeffValid=a=>{let r=0;for(let t=0;t<a.length;t+=1){const e=Number(a.charAt(a.length-1-t)),o=VERHOEFF_P[t%8],s=VERHOEFF_D[r];if(void 0===o||void 0===s)throw new Error("Verhoeff lookup is out of range.");const l=o[e],d=void 0===l?void 0:s[l];if(void 0===d)throw new Error("Aadhaar digits must be 0 to 9.");r=d}return 0===r},normalizeAadhaar=a=>{const r=(0,_text.withoutSpaces)(a);return null===r?null:r.replace(/-/g,"").trim()};exports.normalizeAadhaar=normalizeAadhaar;const validAadhaar=a=>{const r=normalizeAadhaar(a);return null!==r&&RE_AADHAAR.test(r)&&isVerhoeffValid(r)?r:null},isAadhaar=a=>null!==validAadhaar(a);exports.isAadhaar=isAadhaar;const maskAadhaar=a=>{const r=validAadhaar(a);return null===r?null:`XXXX XXXX ${r.slice(-4)}`};exports.maskAadhaar=maskAadhaar;const aadhaarLastFour=a=>{const r=validAadhaar(a);return null===r?null:r.slice(-4)};exports.aadhaarLastFour=aadhaarLastFour;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.recentFinancialYears=exports.parseFinancialYear=exports.financialYearOf=exports.financialYearLabel=exports.currentFinancialYear=void 0;var _indiaTime=require("./indiaTime.js");const MAX_START_YEAR=9998,twoDigits=a=>String(a%100).padStart(2,"0"),fourDigits=a=>String(a).padStart(4,"0"),financialYearLabel=a=>`${a}-${twoDigits(a+1)}`;exports.financialYearLabel=financialYearLabel;const withStartYear=a=>{const e=financialYearLabel(a);return{startYear:a,label:e,displayLabel:`FY ${e}`,assessmentYearLabel:financialYearLabel(a+1),startDate:`${fourDigits(a)}-04-01`,endDate:`${fourDigits(a+1)}-03-31`}},financialYearOf=a=>{const[e,r]=(0,_indiaTime.istDateOf)(a).split("-").map(Number);return withStartYear(r>=4?e:e-1)};exports.financialYearOf=financialYearOf;const currentFinancialYear=(a=new Date)=>financialYearOf(a);exports.currentFinancialYear=currentFinancialYear;const parseFinancialYear=a=>{if("string"!=typeof a)return null;let e=a.trim();/^fy/i.test(e)&&(e=e.slice(2).trimStart());const r=e.indexOf("-"),t=(r<0?e:e.slice(0,r)).trimEnd();if(!/^\d{4}$/.test(t))return null;const
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.recentFinancialYears=exports.parseFinancialYear=exports.financialYearOf=exports.financialYearLabel=exports.currentFinancialYear=void 0;var _indiaTime=require("./indiaTime.js");const MAX_START_YEAR=9998,twoDigits=a=>String(a%100).padStart(2,"0"),fourDigits=a=>String(a).padStart(4,"0"),financialYearLabel=a=>`${a}-${twoDigits(a+1)}`;exports.financialYearLabel=financialYearLabel;const withStartYear=a=>{const e=financialYearLabel(a);return{startYear:a,label:e,displayLabel:`FY ${e}`,assessmentYearLabel:financialYearLabel(a+1),startDate:`${fourDigits(a)}-04-01`,endDate:`${fourDigits(a+1)}-03-31`}},financialYearOf=a=>{const[e,r]=(0,_indiaTime.istDateOf)(a).split("-").map(Number);if(void 0===e||void 0===r)throw new Error("istDateOf returns a yyyy-MM-dd date.");return withStartYear(r>=4?e:e-1)};exports.financialYearOf=financialYearOf;const currentFinancialYear=(a=new Date)=>financialYearOf(a);exports.currentFinancialYear=currentFinancialYear;const parseFinancialYear=a=>{if("string"!=typeof a)return null;let e=a.trim();/^fy/i.test(e)&&(e=e.slice(2).trimStart());const r=e.indexOf("-"),t=(r<0?e:e.slice(0,r)).trimEnd();if(!/^\d{4}$/.test(t))return null;const i=Number(t);if(i<1||i>9998)return null;if(r<0)return withStartYear(i);const n=e.slice(r+1).trimStart(),s=i+1;return n===twoDigits(s)||n===String(s)?withStartYear(i):null};exports.parseFinancialYear=parseFinancialYear;const recentFinancialYears=(a,e=new Date)=>{if(!Number.isInteger(a)||a<1)throw new RangeError(`A count of recent financial years must be a whole number of at least 1, got ${a}.`);const r=currentFinancialYear(e).startYear;return Array.from({length:a},(a,e)=>withStartYear(r-e))};exports.recentFinancialYears=recentFinancialYears;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.whereIn=exports.toSqliteValue=exports.setSqliteImplementation=exports.openDatabase=exports.isSqliteAvailable=exports.fromSqliteBoolean=exports.assertSqlIdentifier=exports.MIGRATIONS_TABLE=exports.DEFAULT_PRAGMAS=void 0;var cache,ExpoSqlite=_interopRequireWildcard(require("expo-sqlite")),_index=require("../logger/index.js"),_expo=require("./adapters/expo.js");function _interopRequireWildcard(e,t){if(!t&&e&&e.__esModule)return e;var r,n,i=Object.defineProperty,a={__proto__:null,default:e};if(Object(e)!==e)return a;if(cache||"function"!=typeof WeakMap||(cache=new WeakMap),cache){if(cache.has(e))return cache.get(e);cache.set(e,a)}for(n in e)"default"!==n&&{}.hasOwnProperty.call(e,n)&&((r=i&&Object.getOwnPropertyDescriptor(e,n))&&(r.get||r.set)?i(a,n,r):a[n]=e[n]);return a}let expoDriver,backend=null;const setSqliteImplementation=e=>{backend=e};exports.setSqliteImplementation=setSqliteImplementation;const hasNativeSqlite=e=>"function"==typeof e?.openDatabaseAsync,resolveDriver=()=>{if(backend)return backend;if(void 0===expoDriver){const e=ExpoSqlite;expoDriver=hasNativeSqlite(e)?(0,_expo.adaptExpoSqlite)(e):null}return expoDriver},isSqliteAvailable=()=>null!==resolveDriver();exports.isSqliteAvailable=isSqliteAvailable;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 _index.Logger.error(t.message),t}return t},MIGRATIONS_TABLE=exports.MIGRATIONS_TABLE="_webority_migrations",IDENTIFIER=/^[A-Za-z_][A-Za-z0-9_]*$/,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};exports.assertSqlIdentifier=assertSqlIdentifier;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},toSqliteValue=e=>void 0===e?null:"boolean"==typeof e?e?1:0:e instanceof Date?e.toISOString():e;exports.toSqliteValue=toSqliteValue;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};exports.fromSqliteBoolean=fromSqliteBoolean;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)}};exports.whereIn=whereIn;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"),a=toSqliteValue(i);null===a?r.push(`${t} IS NULL`):(r.push(`${t} = ?`),n.push(a))}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 a=quoteIdentifier(r,"orderBy column");if(void 0===n)return a;const o=n.toUpperCase();if("ASC"!==o&&"DESC"!==o)throw new Error(`[@webority/mobile-core] Invalid sort direction ${JSON.stringify(n)} in orderBy ${JSON.stringify(e)}. Expected ASC or DESC.`);return`${a} ${o}`}).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)},DEFAULT_PRAGMAS=exports.DEFAULT_PRAGMAS={journal_mode:"WAL",synchronous:"NORMAL",foreign_keys:"ON",busy_timeout:5e3},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.length>0?r[0]: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 _index.Logger.error(`[@webority/mobile-core] SQLite execute failed: ${e}`,t),t}},n=queriesOver(run),{execute:i,select:a,selectOne:o}=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){_index.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){_index.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")),a=n.map(()=>"?");return{sql:`INSERT INTO ${r} (${i.join(", ")}) VALUES (${a.join(", ")})`,params:n.map(([,e])=>toSqliteValue(e))}},findAll=async(e,t,r)=>{const n=quoteIdentifier(e,"table name"),i=buildWhere(t),o=[...i.params];let s=`SELECT * FROM ${n}${i.clause}${buildOrderBy(r?.orderBy)}`;return void 0!==r?.limit?(assertNonNegativeInteger(r.limit,"limit"),s+=" LIMIT ?",o.push(r.limit)):void 0!==r?.offset&&(s+=" LIMIT -1"),void 0!==r?.offset&&(assertNonNegativeInteger(r.offset,"offset"),s+=" OFFSET ?",o.push(r.offset)),a(s,o)},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 o("PRAGMA user_version");let l=Number(i?.user_version??0);if(t.length>0&&!r?.allowDowngrade){const r=t.reduce((e,t)=>Math.max(e,t.version),0);if(l>r)throw new Error(`[@webority/mobile-core] Database "${e}" is at schema version ${l}, 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 a(`SELECT version, checksum FROM ${escapeIdentifier(MIGRATIONS_TABLE)}`),u=new Map(c.map(e=>[Number(e.version),String(e.checksum)]));for(const r of t){if(r.version>l)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>l).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}`)}),l=e.version}return l};return{name:e,execute:i,select:a,selectOne:o,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"),a=Object.entries(t);if(0===a.length)throw new Error(`[@webority/mobile-core] Cannot update ${e} with no values. Pass at least one column to set.`);const o=a.map(([e])=>`${quoteIdentifier(e,"column name")} = ?`),s=a.map(([,e])=>toSqliteValue(e)),l=buildWhere(r);return(await i(`UPDATE ${n} SET ${o.join(", ")}${l.clause}`,[...s,...l.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:a}=insertSql(e,t),o=new Set(r),s=r.map(e=>quoteIdentifier(e,"column name")),l=Object.keys(t).filter(e=>!o.has(e)).map(e=>{const t=quoteIdentifier(e,"column name");return`${t} = excluded.${t}`}),c=l.length>0?`DO UPDATE SET ${l.join(", ")}`:"DO NOTHING";await i(`${n} ON CONFLICT (${s.join(", ")}) ${c}`,a)},findAll:findAll,findOne:async(e,t)=>{const r=await findAll(e,t,{limit:1});return r.length>0?r[0]:null},count:async(e,t)=>{const r=quoteIdentifier(e,"table name"),n=buildWhere(t),i=await o(`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 o("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?",[e])},createTable:async(e,t,r)=>{const n=quoteIdentifier(e,"table name"),a=Object.entries(t);if(0===a.length)throw new Error(`[@webority/mobile-core] Cannot create table ${e} with no columns.`);const o=a.map(([e,t])=>`${quoteIdentifier(e,"column name")} ${assertColumnDefinition(t,e)}`),s=!1===r?.ifNotExists?"":"IF NOT EXISTS ";await i(`CREATE TABLE ${s}${n} (${o.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())}},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};exports.openDatabase=openDatabase;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.whereIn=exports.toSqliteValue=exports.setSqliteImplementation=exports.openDatabase=exports.isSqliteAvailable=exports.fromSqliteBoolean=exports.assertSqlIdentifier=exports.MIGRATIONS_TABLE=exports.DEFAULT_PRAGMAS=void 0;var cache,ExpoSqlite=_interopRequireWildcard(require("expo-sqlite")),_index=require("../logger/index.js"),_expo=require("./adapters/expo.js");function _interopRequireWildcard(e,t){if(!t&&e&&e.__esModule)return e;var r,n,i=Object.defineProperty,a={__proto__:null,default:e};if(Object(e)!==e)return a;if(cache||"function"!=typeof WeakMap||(cache=new WeakMap),cache){if(cache.has(e))return cache.get(e);cache.set(e,a)}for(n in e)"default"!==n&&{}.hasOwnProperty.call(e,n)&&((r=i&&Object.getOwnPropertyDescriptor(e,n))&&(r.get||r.set)?i(a,n,r):a[n]=e[n]);return a}let expoDriver,backend=null;const setSqliteImplementation=e=>{backend=e};exports.setSqliteImplementation=setSqliteImplementation;const hasNativeSqlite=e=>"function"==typeof e?.openDatabaseAsync,resolveDriver=()=>{if(backend)return backend;if(void 0===expoDriver){const e=ExpoSqlite;expoDriver=hasNativeSqlite(e)?(0,_expo.adaptExpoSqlite)(e):null}return expoDriver},isSqliteAvailable=()=>null!==resolveDriver();exports.isSqliteAvailable=isSqliteAvailable;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 _index.Logger.error(t.message),t}return t},MIGRATIONS_TABLE=exports.MIGRATIONS_TABLE="_webority_migrations",IDENTIFIER=/^[A-Za-z_][A-Za-z0-9_]*$/,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};exports.assertSqlIdentifier=assertSqlIdentifier;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},toSqliteValue=e=>void 0===e?null:"boolean"==typeof e?e?1:0:e instanceof Date?e.toISOString():e;exports.toSqliteValue=toSqliteValue;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};exports.fromSqliteBoolean=fromSqliteBoolean;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)}};exports.whereIn=whereIn;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"),a=toSqliteValue(i);null===a?r.push(`${t} IS NULL`):(r.push(`${t} = ?`),n.push(a))}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 a=quoteIdentifier(r,"orderBy column");if(void 0===n)return a;const o=n.toUpperCase();if("ASC"!==o&&"DESC"!==o)throw new Error(`[@webority/mobile-core] Invalid sort direction ${JSON.stringify(n)} in orderBy ${JSON.stringify(e)}. Expected ASC or DESC.`);return`${a} ${o}`}).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)},DEFAULT_PRAGMAS=exports.DEFAULT_PRAGMAS={journal_mode:"WAL",synchronous:"NORMAL",foreign_keys:"ON",busy_timeout:5e3},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 _index.Logger.error(`[@webority/mobile-core] SQLite execute failed: ${e}`,t),t}},n=queriesOver(run),{execute:i,select:a,selectOne:o}=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){_index.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){_index.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")),a=n.map(()=>"?");return{sql:`INSERT INTO ${r} (${i.join(", ")}) VALUES (${a.join(", ")})`,params:n.map(([,e])=>toSqliteValue(e))}},findAll=async(e,t,r)=>{const n=quoteIdentifier(e,"table name"),i=buildWhere(t),o=[...i.params];let s=`SELECT * FROM ${n}${i.clause}${buildOrderBy(r?.orderBy)}`;return void 0!==r?.limit?(assertNonNegativeInteger(r.limit,"limit"),s+=" LIMIT ?",o.push(r.limit)):void 0!==r?.offset&&(s+=" LIMIT -1"),void 0!==r?.offset&&(assertNonNegativeInteger(r.offset,"offset"),s+=" OFFSET ?",o.push(r.offset)),a(s,o)},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 o("PRAGMA user_version");let l=Number(i?.user_version??0);if(t.length>0&&!r?.allowDowngrade){const r=t.reduce((e,t)=>Math.max(e,t.version),0);if(l>r)throw new Error(`[@webority/mobile-core] Database "${e}" is at schema version ${l}, 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 a(`SELECT version, checksum FROM ${escapeIdentifier(MIGRATIONS_TABLE)}`),u=new Map(c.map(e=>[Number(e.version),String(e.checksum)]));for(const r of t){if(r.version>l)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>l).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}`)}),l=e.version}return l};return{name:e,execute:i,select:a,selectOne:o,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"),a=Object.entries(t);if(0===a.length)throw new Error(`[@webority/mobile-core] Cannot update ${e} with no values. Pass at least one column to set.`);const o=a.map(([e])=>`${quoteIdentifier(e,"column name")} = ?`),s=a.map(([,e])=>toSqliteValue(e)),l=buildWhere(r);return(await i(`UPDATE ${n} SET ${o.join(", ")}${l.clause}`,[...s,...l.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:a}=insertSql(e,t),o=new Set(r),s=r.map(e=>quoteIdentifier(e,"column name")),l=Object.keys(t).filter(e=>!o.has(e)).map(e=>{const t=quoteIdentifier(e,"column name");return`${t} = excluded.${t}`}),c=l.length>0?`DO UPDATE SET ${l.join(", ")}`:"DO NOTHING";await i(`${n} ON CONFLICT (${s.join(", ")}) ${c}`,a)},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 o(`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 o("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?",[e])},createTable:async(e,t,r)=>{const n=quoteIdentifier(e,"table name"),a=Object.entries(t);if(0===a.length)throw new Error(`[@webority/mobile-core] Cannot create table ${e} with no columns.`);const o=a.map(([e,t])=>`${quoteIdentifier(e,"column name")} ${assertColumnDefinition(t,e)}`),s=!1===r?.ifNotExists?"":"IF NOT EXISTS ";await i(`CREATE TABLE ${s}${n} (${o.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())}},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};exports.openDatabase=openDatabase;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const cryptoApi=()=>globalThis.crypto,randomBytes16=()=>{const t=new Uint8Array(16),o=cryptoApi();if("function"==typeof o?.getRandomValues)o.getRandomValues(t);else for(let o=0;o<t.length;o+=1)t[o]=Math.floor(256*Math.random());return t},formatUuid=t=>{const o=Array.from(t,t=>t.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,32)}`};export const newIdempotencyKey=()=>{const t=cryptoApi();if("function"==typeof t?.randomUUID)return t.randomUUID();const o=randomBytes16()
|
|
1
|
+
"use strict";const cryptoApi=()=>globalThis.crypto,randomBytes16=()=>{const t=new Uint8Array(16),o=cryptoApi();if("function"==typeof o?.getRandomValues)o.getRandomValues(t);else for(let o=0;o<t.length;o+=1)t[o]=Math.floor(256*Math.random());return t},formatUuid=t=>{const o=Array.from(t,t=>t.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,32)}`};export const newIdempotencyKey=()=>{const t=cryptoApi();if("function"==typeof t?.randomUUID)return t.randomUUID();const o=Array.from(randomBytes16(),(t,o)=>6===o?15&t|64:8===o?63&t|128:t);return formatUuid(o)};
|
package/lib/module/auth/jwt.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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=
|
|
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+/",sextetAt=(e,t)=>{const r=e.charAt(t);return""===r?-1:BASE64_ALPHABET.indexOf(r)},decodeBase64Fallback=e=>{let t="";for(let r=0;r<e.length;r+=4){const o=sextetAt(e,r),n=sextetAt(e,r+1),a=sextetAt(e,r+2),s=sextetAt(e,r+3),c=Math.max(o,0)<<18|Math.max(n,0)<<12|Math.max(a,0)<<6|Math.max(s,0);t+=String.fromCharCode(c>>16&255),-1!==a&&(t+=String.fromCharCode(c>>8&255)),-1!==s&&(t+=String.fromCharCode(255&c))}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("."),r=3===t.length?t[1]:void 0;if(void 0===r)return Logger.warn("[jwt] decodeJWT: token is not a valid JWT (expected 3 segments)"),null;try{const e=utf8FromBinary(decodeBase64(base64UrlToBase64(r)));return JSON.parse(e)}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
|
-
"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 UNREACHABLE_MESSAGE="We couldn't reach the server. Check your connection and 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";export const OFFLINE_CODE="offline";const INTERNAL_ERROR_CODE="internal_error",MAX_MESSAGE_LENGTH=300,requestFailedMessage=e=>`Request failed (${e})`,FLEET_DEFAULT_REFUSALS={401:{code:"unauthorized",sentence:"Please sign in to continue."},403:{code:"forbidden",sentence:"You do not have access to this."}},isDict=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),nonEmptyString=e=>"string"==typeof e&&e.trim().length>0?e:null,fleetDefaultRefusalSentence=(e,t)=>{const n=FLEET_DEFAULT_REFUSALS[e];if(void 0===n||null===t||t.code!==n.code)return null;const r=nonEmptyString(t.detail);return null===r||r===n.sentence?n.sentence:null},looksLikeDiagnostics=e=>e.length>300||/^\s*</.test(e)||e.includes("\n at ")||/(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,n)=>{const r=toFieldPath(t);""===r?e.form??=n:r in e.fields||(e.fields[r]=n)},readErrors=e=>{const t={fields:{},form:null};if(Array.isArray(e)){for(const n of e){if(!isDict(n))continue;const e=nonEmptyString(n.message);null!==e&&addError(t,"string"==typeof n.field?n.field:"",e)}return t}if(!isDict(e))return t;for(const[n,r]of Object.entries(e)){const e=firstMessage(r);null!==e&&addError(t,n,e)}return 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,diagnostic:null,...e}),requestTraceId=e=>{const t=isDict(e.config)?e.config.headers:void 0;if(!isDict(t))return null;const n="function"==typeof t.get?t.get("traceparent"):t.traceparent??t.Traceparent,r="string"==typeof n?/^00-([0-9a-f]{32})-[0-9a-f]{16}-[0-9a-f]{2}$/.exec(n):null;return r
|
|
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 UNREACHABLE_MESSAGE="We couldn't reach the server. Check your connection and 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";export const OFFLINE_CODE="offline";const INTERNAL_ERROR_CODE="internal_error",MAX_MESSAGE_LENGTH=300,requestFailedMessage=e=>`Request failed (${e})`,FLEET_DEFAULT_REFUSALS={401:{code:"unauthorized",sentence:"Please sign in to continue."},403:{code:"forbidden",sentence:"You do not have access to this."}},isDict=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),nonEmptyString=e=>"string"==typeof e&&e.trim().length>0?e:null,fleetDefaultRefusalSentence=(e,t)=>{const n=FLEET_DEFAULT_REFUSALS[e];if(void 0===n||null===t||t.code!==n.code)return null;const r=nonEmptyString(t.detail);return null===r||r===n.sentence?n.sentence:null},looksLikeDiagnostics=e=>e.length>300||/^\s*</.test(e)||e.includes("\n at ")||/(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,n)=>{const r=toFieldPath(t);""===r?e.form??=n:r in e.fields||(e.fields[r]=n)},readErrors=e=>{const t={fields:{},form:null};if(Array.isArray(e)){for(const n of e){if(!isDict(n))continue;const e=nonEmptyString(n.message);null!==e&&addError(t,"string"==typeof n.field?n.field:"",e)}return t}if(!isDict(e))return t;for(const[n,r]of Object.entries(e)){const e=firstMessage(r);null!==e&&addError(t,n,e)}return 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,diagnostic:null,...e}),requestTraceId=e=>{const t=isDict(e.config)?e.config.headers:void 0;if(!isDict(t))return null;const n="function"==typeof t.get?t.get("traceparent"):t.traceparent??t.Traceparent,r="string"==typeof n?/^00-([0-9a-f]{32})-[0-9a-f]{16}-[0-9a-f]{2}$/.exec(n):null;return r?.[1]??null},fromNoResponse=e=>{const t=nonEmptyString(e.code),n=nonEmptyString(e.name),r=nonEmptyString(e.message),o=requestTraceId(e);return build("CanceledError"===n||"ERR_CANCELED"===t?{code:"request_canceled",message:UNEXPECTED_MESSAGE,traceId:o,diagnostic:r}:"ECONNABORTED"===t||"ETIMEDOUT"===t?{code:"timeout",message:TIMEOUT_MESSAGE,offline:!0,traceId:o,diagnostic:r}:"RequestOfflineError"===n?{code:"offline",message:OFFLINE_MESSAGE,offline:!0,traceId:o,diagnostic:r}:"ERR_NETWORK"===t||"Network Error"===r||"Network request failed"===r?{code:"network",message:UNREACHABLE_MESSAGE,offline:!0,traceId:o,diagnostic:r}:{message:UNEXPECTED_MESSAGE,traceId:o,diagnostic:r})};export function extractApiError(e){if(isApiError(e))return e;if("string"==typeof e)return build({message:userSafe(e)??UNEXPECTED_MESSAGE,diagnostic:e||null});if(!isDict(e))return build({message:UNEXPECTED_MESSAGE,diagnostic:null==e?null:String(e)});if(!0===e.isContractError)return build({code:"contract_error",message:userSafe(e.message)??UNEXPECTED_MESSAGE,diagnostic:nonEmptyString(e.message)});const t=isDict(e.response)?e.response:null,n="number"==typeof t?.status?t.status:"number"==typeof e.status?e.status:0,r=t?t.data:e.body;if(0===n&&null==r)return fromNoResponse(e);const o=isDict(r)?r:null,{fields:s,form:i}=readErrors(o?.errors),a=nonEmptyString(o?.code),E=nonEmptyString(o?.traceId)??requestTraceId(e),c=nonEmptyString(o?.detail)??nonEmptyString(o?.title)??nonEmptyString(r)??nonEmptyString(e.message);let l;if(n>=500){l=(null!==a&&"internal_error"!==a?userSafe(o?.detail):null)??SERVER_FAILURE_MESSAGE}else l=fleetDefaultRefusalSentence(n,o)??userSafe(Object.values(s)[0])??userSafe(i)??userSafe(o?.detail)??userSafe(o?.title)??userSafe(r)??(n?requestFailedMessage(n):UNEXPECTED_MESSAGE);return build({code:a,message:l,fieldErrors:s,status:n,traceId:E,diagnostic:c})}export const isNoResponse=e=>extractApiError(e).offline;export function apiErrorMessage(e,t){const n=extractApiError(e);if(n.offline||null!==t&&!t)return n.message;return n.message===SERVER_FAILURE_MESSAGE||"request_canceled"===n.code||n.message===UNEXPECTED_MESSAGE||n.message===requestFailedMessage(n.status)?t??null:n.message}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const DEFAULTS={zone:"IST",locale:"en-IN",empty:"-"},SEPARATORS={PointWithCommaGroups:{decimal:".",group:","},CommaWithPointGroups:{decimal:",",group:"."},CommaWithSpaceGroups:{decimal:",",group:" "},PointWithSpaceGroups:{decimal:".",group:" "}},DATE_ORDERS=["DayMonthNameYear","DayMonthYear","MonthDayYear","YearMonthDay"];let current={...DEFAULTS},configured=new Set;export const configureFormatters=
|
|
1
|
+
"use strict";const DEFAULTS={zone:"IST",locale:"en-IN",empty:"-"},SEPARATORS={PointWithCommaGroups:{decimal:".",group:","},CommaWithPointGroups:{decimal:",",group:"."},CommaWithSpaceGroups:{decimal:",",group:" "},PointWithSpaceGroups:{decimal:".",group:" "}},DATE_ORDERS=["DayMonthNameYear","DayMonthYear","MonthDayYear","YearMonthDay"];let current={...DEFAULTS},configured=new Set;export const configureFormatters=r=>{if(void 0===r)return current={...DEFAULTS},void(configured=new Set);if(void 0!==r.numberStyle&&!Object.hasOwn(SEPARATORS,r.numberStyle))throw new RangeError(`Unknown number style "${r.numberStyle}"; expected one of ${Object.keys(SEPARATORS).join(", ")}.`);if(void 0!==r.dateOrder&&!DATE_ORDERS.includes(r.dateOrder))throw new RangeError(`Unknown date order "${r.dateOrder}"; expected one of ${DATE_ORDERS.join(", ")}.`);for(const e of Object.keys(r)){const t=r[e];void 0!==t&&(current={...current,[e]:t},configured.add(e))}};export const getFormatterConfig=()=>({...current});export const isFormatterConfigured=r=>configured.has(r);export const configuredLocale=()=>configured.has("locale")?current.locale:null;export const groupingForLocale=r=>/-IN(?:-|$)/i.test(r)?"indian":"international";export const numberSeparators=()=>void 0===current.numberStyle?null:SEPARATORS[current.numberStyle];const localeMarks=new Map,digitsOf=r=>{const e=new Intl.NumberFormat(r,{useGrouping:!1}),t=new Set;for(let r=0;r<=9;r++)t.add(e.format(r));return t},separatorRuns=(r,e)=>{const t=[];let o=[],n=!1;for(const a of r)e.has(a)?(o.length>0&&(t.push(o),o=[]),n=!0):n&&o.push(a);return t},marksOf=r=>{const e=localeMarks.get(r);if(void 0!==e)return e;const t=digitsOf(r),o=new Intl.NumberFormat(r,{useGrouping:!0,minimumFractionDigits:1,maximumFractionDigits:1}).format(11111.5),n=separatorRuns(Array.from(o),t),a={digits:t,decimal:n.at(-1)??null,group:n.length>=2?n.at(0)??null:null};return localeMarks.set(r,a),a},isDigitAt=(r,e,t)=>{const o=e>=0?r.at(e):void 0;return void 0!==o&&t.has(o)},swapMarks=(r,e,t)=>{const o=Array.from(r);let n="",a=0;for(;a<o.length;){const r=t.find(({mark:r})=>isDigitAt(o,a-1,e)&&r.every((r,e)=>o[a+e]===r)&&isDigitAt(o,a+r.length,e));void 0===r?(n+=o[a],a+=1):(n+=r.to,a+=r.mark.length)}return n};export const styledNumber=(r,e)=>{const t=numberSeparators();if(null===t)return r.format(e);const{digits:o,decimal:n,group:a}=marksOf(r.resolvedOptions().locale),i=[];return null!==n&&i.push({mark:n,to:t.decimal}),null!==a&&i.push({mark:a,to:t.group}),swapMarks(r.format(e),o,i)};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{withoutSpaces}from"./text.js";const RE_AADHAAR=/^[2-9][0-9]{11}$/,VERHOEFF_D=[[0,1,2,3,4,5,6,7,8,9],[1,2,3,4,0,6,7,8,9,5],[2,3,4,0,1,7,8,9,5,6],[3,4,0,1,2,8,9,5,6,7],[4,0,1,2,3,9,5,6,7,8],[5,9,8,7,6,0,4,3,2,1],[6,5,9,8,7,1,0,4,3,2],[7,6,5,9,8,2,1,0,4,3],[8,7,6,5,9,3,2,1,0,4],[9,8,7,6,5,4,3,2,1,0]],VERHOEFF_P=[[0,1,2,3,4,5,6,7,8,9],[1,5,7,6,2,8,3,0,9,4],[5,8,0,3,7,9,6,1,4,2],[8,9,1,6,0,4,3,5,2,7],[9,4,5,3,1,2,6,8,7,0],[4,2,8,6,5,7,3,9,0,1],[2,7,9,3,8,0,6,4,1,5],[7,0,4,6,9,1,3,2,5,8]],isVerhoeffValid=
|
|
1
|
+
"use strict";import{withoutSpaces}from"./text.js";const RE_AADHAAR=/^[2-9][0-9]{11}$/,VERHOEFF_D=[[0,1,2,3,4,5,6,7,8,9],[1,2,3,4,0,6,7,8,9,5],[2,3,4,0,1,7,8,9,5,6],[3,4,0,1,2,8,9,5,6,7],[4,0,1,2,3,9,5,6,7,8],[5,9,8,7,6,0,4,3,2,1],[6,5,9,8,7,1,0,4,3,2],[7,6,5,9,8,2,1,0,4,3],[8,7,6,5,9,3,2,1,0,4],[9,8,7,6,5,4,3,2,1,0]],VERHOEFF_P=[[0,1,2,3,4,5,6,7,8,9],[1,5,7,6,2,8,3,0,9,4],[5,8,0,3,7,9,6,1,4,2],[8,9,1,6,0,4,3,5,2,7],[9,4,5,3,1,2,6,8,7,0],[4,2,8,6,5,7,3,9,0,1],[2,7,9,3,8,0,6,4,1,5],[7,0,4,6,9,1,3,2,5,8]],isVerhoeffValid=r=>{let a=0;for(let t=0;t<r.length;t+=1){const o=Number(r.charAt(r.length-1-t)),e=VERHOEFF_P[t%8],l=VERHOEFF_D[a];if(void 0===e||void 0===l)throw new Error("Verhoeff lookup is out of range.");const n=e[o],i=void 0===n?void 0:l[n];if(void 0===i)throw new Error("Aadhaar digits must be 0 to 9.");a=i}return 0===a};export const normalizeAadhaar=r=>{const a=withoutSpaces(r);return null===a?null:a.replace(/-/g,"").trim()};const validAadhaar=r=>{const a=normalizeAadhaar(r);return null!==a&&RE_AADHAAR.test(a)&&isVerhoeffValid(a)?a:null};export const isAadhaar=r=>null!==validAadhaar(r);export const maskAadhaar=r=>{const a=validAadhaar(r);return null===a?null:`XXXX XXXX ${a.slice(-4)}`};export const aadhaarLastFour=r=>{const a=validAadhaar(r);return null===a?null:a.slice(-4)};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{istDateOf}from"./indiaTime.js";const MAX_START_YEAR=9998,twoDigits=t=>String(t%100).padStart(2,"0"),fourDigits=t=>String(t).padStart(4,"0");export const financialYearLabel=t=>`${t}-${twoDigits(t+1)}`;const withStartYear=t=>{const r=financialYearLabel(t);return{startYear:t,label:r,displayLabel:`FY ${r}`,assessmentYearLabel:financialYearLabel(t+1),startDate:`${fourDigits(t)}-04-01`,endDate:`${fourDigits(t+1)}-03-31`}};export const financialYearOf=t=>{const[r,e]=istDateOf(t).split("-").map(Number);return withStartYear(e>=4?r:r-1)};export const currentFinancialYear=(t=new Date)=>financialYearOf(t);export const parseFinancialYear=t=>{if("string"!=typeof t)return null;let r=t.trim();/^fy/i.test(r)&&(r=r.slice(2).trimStart());const e=r.indexOf("-"),a=(e<0?r:r.slice(0,e)).trimEnd();if(!/^\d{4}$/.test(a))return null;const
|
|
1
|
+
"use strict";import{istDateOf}from"./indiaTime.js";const MAX_START_YEAR=9998,twoDigits=t=>String(t%100).padStart(2,"0"),fourDigits=t=>String(t).padStart(4,"0");export const financialYearLabel=t=>`${t}-${twoDigits(t+1)}`;const withStartYear=t=>{const r=financialYearLabel(t);return{startYear:t,label:r,displayLabel:`FY ${r}`,assessmentYearLabel:financialYearLabel(t+1),startDate:`${fourDigits(t)}-04-01`,endDate:`${fourDigits(t+1)}-03-31`}};export const financialYearOf=t=>{const[r,e]=istDateOf(t).split("-").map(Number);if(void 0===r||void 0===e)throw new Error("istDateOf returns a yyyy-MM-dd date.");return withStartYear(e>=4?r:r-1)};export const currentFinancialYear=(t=new Date)=>financialYearOf(t);export const parseFinancialYear=t=>{if("string"!=typeof t)return null;let r=t.trim();/^fy/i.test(r)&&(r=r.slice(2).trimStart());const e=r.indexOf("-"),a=(e<0?r:r.slice(0,e)).trimEnd();if(!/^\d{4}$/.test(a))return null;const i=Number(a);if(i<1||i>9998)return null;if(e<0)return withStartYear(i);const n=r.slice(e+1).trimStart(),s=i+1;return n===twoDigits(s)||n===String(s)?withStartYear(i):null};export const recentFinancialYears=(t,r=new Date)=>{if(!Number.isInteger(t)||t<1)throw new RangeError(`A count of recent financial years must be a whole number of at least 1, got ${t}.`);const e=currentFinancialYear(r).startYear;return Array.from({length:t},(t,r)=>withStartYear(e-r))};
|
|
@@ -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.length>0?r[0]: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.length>0?r[0]: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{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};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webority/mobile-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.147.0",
|
|
4
4
|
"description": "Platform layer for Webority React Native apps: HTTP clients, auth/token storage, config, logging, formatters, validators, network status, permissions, storage, version checks and over-the-air updates. No UI.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"react-native",
|