@webority/mobile-core 0.144.1 → 0.145.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/formatters/currency.js +1 -1
- package/lib/commonjs/formatters/date.js +1 -1
- package/lib/commonjs/formatters/house.js +1 -1
- package/lib/commonjs/formatters/number.js +1 -1
- package/lib/commonjs/sqlite/index.js +1 -1
- package/lib/module/formatters/currency.js +1 -1
- package/lib/module/formatters/date.js +1 -1
- package/lib/module/formatters/house.js +1 -1
- package/lib/module/formatters/number.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.formatCurrency=void 0;var _formatConfig=require("./formatConfig.js"),_intlCache=require("./intlCache.js");const hasIntlNumber=()=>"undefined"!=typeof Intl&&"function"==typeof Intl.NumberFormat,indianGroupingFallback=(r,e)=>{const{decimal:t,group:n}=(0,_formatConfig.numberSeparators)()??{decimal:".",group:","},
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.formatCurrency=void 0;var _formatConfig=require("./formatConfig.js"),_intlCache=require("./intlCache.js");const hasIntlNumber=()=>"undefined"!=typeof Intl&&"function"==typeof Intl.NumberFormat,indianGroupingFallback=(r,e)=>{const{decimal:t,group:n}=(0,_formatConfig.numberSeparators)()??{decimal:".",group:","},o=r<0?"-":"",i=Math.abs(r).toFixed(e),[c,a]=i.split("."),m=c.length>3?c.slice(-3):c,u=c.length>3?c.slice(0,-3):"";return o+(u?u.replace(/\B(?=(\d{2})+(?!\d))/g,n)+n+m:m)+(a?`${t}${a}`:"")},toAmount=r=>{if(null==r||"string"==typeof r&&""===r.trim())return null;const e="number"==typeof r?r:Number(r);return Number.isFinite(e)?e:null},currencyDigits=(r,e)=>(0,_intlCache.numberFormat)(r,{style:"currency",currency:e}).resolvedOptions().maximumFractionDigits??2,formatCurrency=(r,e)=>{if(!e?.currency)throw new TypeError('[@webority/mobile-core] formatCurrency needs options.currency, an ISO 4217 code such as "INR".');const{currency:t,locale:n=(0,_formatConfig.configuredLocale)()??"en-IN",minimumFractionDigits:o,maximumFractionDigits:i,stripSymbol:c=!1,empty:a=((0,_formatConfig.isFormatterConfigured)("locale")||(0,_formatConfig.isFormatterConfigured)("empty")?(0,_formatConfig.getFormatterConfig)().empty:""),...m}=e,u=toAmount(r);if(null===u)return a;if(hasIntlNumber())try{const r=i??currencyDigits(n,t),e=o??(Number.isInteger(u)?0:r),a=(0,_formatConfig.styledNumber)((0,_intlCache.numberFormat)(n,{...m,style:"currency",currency:t,minimumFractionDigits:e,maximumFractionDigits:Math.max(e,r)}),u);return c?a.replace(/[^\d,.\s\-+]/g,"").trim():a}catch(r){if(r instanceof RangeError)throw new RangeError(`[@webority/mobile-core] formatCurrency rejected currency "${t}" or locale "${n}": ${r.message}`,{cause:r});throw r}const s=indianGroupingFallback(u,o??(Number.isInteger(u)?0:2));return c?s:"INR"===t?`₹${s}`:`${t} ${s}`};exports.formatCurrency=formatCurrency;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.formatDate=formatDate,exports.formatDateTime=formatDateTime,exports.formatRelativeTime=void 0,exports.formatTime=formatTime;var _house=require("./house.js"),_intlCache=require("./intlCache.js");const toDate=
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.formatDate=formatDate,exports.formatDateTime=formatDateTime,exports.formatRelativeTime=void 0,exports.formatTime=formatTime;var _house=require("./house.js"),_intlCache=require("./intlCache.js");const toDate=e=>{if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;const t=new Date(e);return Number.isNaN(t.getTime())?null:t},hasIntl=()=>"undefined"!=typeof Intl&&"function"==typeof Intl.DateTimeFormat,PAD=e=>e<10?`0${e}`:`${e}`,fallbackDate=(e,t)=>{const r=PAD(e.getDate()),a=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][e.getMonth()],o=["January","February","March","April","May","June","July","August","September","October","November","December"][e.getMonth()],n=e.getFullYear(),i=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][e.getDay()];switch(t){case"short":return`${r}/${PAD(e.getMonth()+1)}/${n}`;case"long":return`${r} ${o} ${n}`;case"full":return`${i}, ${r} ${o} ${n}`;default:return`${r} ${a} ${n}`}},fallbackTime=(e,t)=>{const r=PAD(e.getHours()),a=PAD(e.getMinutes());if("short"===t)return`${r}:${a}`;return`${r}:${a}:${PAD(e.getSeconds())}`},isStyle=e=>"string"==typeof e;function formatDate(e,t,r="en-IN"){if(!isStyle(t))return(0,_house.formatDate)(e,t);const a=t,o=toDate(e);if(!o)return"";if(hasIntl())try{return(0,_intlCache.dateTimeFormat)(r,{dateStyle:a}).format(o)}catch(e){if(e instanceof RangeError)throw new RangeError(`[@webority/mobile-core] formatDate rejected style "${a}" or locale "${r}": ${e.message}`,{cause:e});throw e}return fallbackDate(o,a)}function formatTime(e,t,r="en-IN"){if(!isStyle(t))return(0,_house.formatTime)(e,t);const a=t,o=toDate(e);if(!o)return"";if(hasIntl())try{return(0,_intlCache.dateTimeFormat)(r,{timeStyle:a}).format(o)}catch(e){if(e instanceof RangeError)throw new RangeError(`[@webority/mobile-core] formatTime rejected style "${a}" or locale "${r}": ${e.message}`,{cause:e});throw e}return fallbackTime(o,a)}function formatDateTime(e,t,r="short",a="en-IN"){if(!isStyle(t))return(0,_house.formatDateTime)(e,t);const o=t,n=toDate(e);if(!n)return"";if(hasIntl())try{return(0,_intlCache.dateTimeFormat)(a,{dateStyle:o,timeStyle:r}).format(n)}catch(e){if(e instanceof RangeError)throw new RangeError(`[@webority/mobile-core] formatDateTime rejected styles "${o}"/"${r}" or locale "${a}": ${e.message}`,{cause:e});throw e}return`${fallbackDate(n,o)}, ${fallbackTime(n,r)}`}const SECOND=1e3,MINUTE=6e4,HOUR=36e5,DAY=24*HOUR,WEEK=7*DAY,MONTH=30*DAY,YEAR=365*DAY,formatRelativeTime=(e,t=new Date,r="en-IN")=>{const a=toDate(e),o=toDate(t);if(!a||!o)return"";const n=a.getTime()-o.getTime(),i=Math.abs(n);let s,m;i<6e4?(s="second",m=Math.round(n/1e3)):i<HOUR?(s="minute",m=Math.round(n/6e4)):i<DAY?(s="hour",m=Math.round(n/HOUR)):i<WEEK?(s="day",m=Math.round(n/DAY)):i<MONTH?(s="week",m=Math.round(n/WEEK)):i<YEAR?(s="month",m=Math.round(n/MONTH)):(s="year",m=Math.round(n/YEAR));const u=hasIntl()?Intl.RelativeTimeFormat:void 0;if("function"==typeof u)try{return(0,_intlCache.relativeTimeFormat)(u,r).format(m,s)}catch(e){if(e instanceof RangeError)throw new RangeError(`[@webority/mobile-core] formatRelativeTime rejected locale "${r}": ${e.message}`,{cause:e});throw e}const l=m<0,c=Math.abs(m),f=1===c?s:`${s}s`;return l?`${c} ${f} ago`:`in ${c} ${f}`};exports.formatRelativeTime=formatRelativeTime;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.formatTime=exports.formatRelative=exports.formatPercent=exports.formatNumber=exports.formatMinor=exports.formatDateTime=exports.formatDate=void 0;var _formatConfig=require("./formatConfig.js"),_intlCache=require("./intlCache.js");const MONTHS=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],IST_OFFSET_MINUTES=330,IST_NAMES=["IST","Asia/Kolkata","Asia/Calcutta"],DATE_ONLY=/^\d{4}-\d{2}-\d{2}$/,pad2=t=>t<10?`0${t}`:`${t}`,emptyOf=t=>t??(0,_formatConfig.getFormatterConfig)().empty,toInstant=t=>{if(null==t||""===t)return null;const e=t instanceof Date?t:new Date("string"==typeof t?t.trim():t);return Number.isNaN(e.getTime())?null:e},isDateOnly=t=>"string"==typeof t&&DATE_ONLY.test(t.trim()),gmtLabel=t=>{if(0===t)return"GMT";const e=t>0?"+":"-",r=Math.abs(t),n=r%60;return`GMT${e}${Math.floor(r/60)}${0===n?"":`:${pad2(n)}`}`},shifted=(t,e,r)=>{const n=new Date(t.getTime()+6e4*e);return{year:n.getUTCFullYear(),month:n.getUTCMonth(),day:n.getUTCDate(),hour:n.getUTCHours(),minute:n.getUTCMinutes(),label:r}},inIanaZone=(t,e)=>{const r=(0,_intlCache.dateTimeFormat)("en-US",{timeZone:e,year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",hour12:!1}).formatToParts(t),read=t=>Number.parseInt(r.find(e=>e.type===t)?.value??"",10),n=read("year"),o=read("month")-1,i=read("day"),a=read("hour")%24,m=read("minute"),l=Date.UTC(n,o,i,a,m),u=Math.round((l-6e4*Math.floor(t.getTime()/6e4))/6e4);return{year:n,month:o,day:i,hour:a,minute:m,label:gmtLabel(u)}},wallClock=(t,e)=>IST_NAMES.includes(e)?shifted(t,330,"IST"):"UTC"===e?shifted(t,0,"UTC"):"viewer"===e?{year:t.getFullYear(),month:t.getMonth(),day:t.getDate(),hour:t.getHours(),minute:t.getMinutes(),label:gmtLabel(-t.getTimezoneOffset())}:inIanaZone(t,e),hourCycleOf=t=>t.hourCycle??12,dayMonthYear=t=>`${pad2(t.day)}-${MONTHS[t.month]}-${t.year}`,numericDate=(t,e)=>{const r=pad2(t.day),n=pad2(t.month+1),o=String(t.year).padStart(4,"0");return"DayMonthYear"===e?`${r}/${n}/${o}`:"MonthDayYear"===e?`${n}/${r}/${o}`:`${o}-${n}-${r}`},clockTime=(t,e)=>24===e?`${pad2(t.hour)}:${pad2(t.minute)}`:`${t.hour%12||12}:${pad2(t.minute)} ${t.hour<12?"AM":"PM"}`,labelled=(t,e)=>e??!IST_NAMES.includes(t),withLabel=(t,e,r,n)=>labelled(r,n)?`${t} ${e.label}`:t,intlZone=t=>{if("viewer"!==t)return IST_NAMES.includes(t)?"Asia/Kolkata":t},localeDayMonthYear=(t,e,r)=>{const n=(0,_intlCache.dateTimeFormat)(e,{day:"2-digit",month:"short",year:"numeric",timeZone:r}).formatToParts(t),part=t=>n.find(e=>e.type===t)?.value??"";return`${part("day")}-${part("month").replace(".","")}-${part("year")}`},dateText=(t,e)=>{const r=(0,_formatConfig.getFormatterConfig)().dateOrder??"DayMonthNameYear";if("DayMonthNameYear"!==r)return numericDate(wallClock(t,e),r);const n=(0,_formatConfig.configuredLocale)();return n?localeDayMonthYear(t,n,intlZone(e)):dayMonthYear(wallClock(t,e))},localeClock=(t,e,r,n)=>(0,_intlCache.dateTimeFormat)(e,{hour:"2-digit",minute:"2-digit",timeZone:intlZone(r),timeZoneName:labelled(r,n.zoneLabel)?"short":void 0,hourCycle:void 0===n.hourCycle?void 0:24===n.hourCycle?"h23":"h12"}).format(t),formatDate=(t,e={})=>{const r=toInstant(t);return r?dateText(r,isDateOnly(t)?"UTC":e.zone??(0,_formatConfig.getFormatterConfig)().zone):emptyOf(e.empty)};exports.formatDate=formatDate;const formatTime=(t,e={})=>{const r=toInstant(t);if(!r)return emptyOf(e.empty);const n=e.zone??(0,_formatConfig.getFormatterConfig)().zone,o=(0,_formatConfig.configuredLocale)();if(o)return localeClock(r,o,n,e);const i=wallClock(r,n);return withLabel(clockTime(i,hourCycleOf(e)),i,n,e.zoneLabel)};exports.formatTime=formatTime;const formatDateTime=(t,e={})=>{const r=toInstant(t);if(!r)return emptyOf(e.empty);const n=e.zone??(0,_formatConfig.getFormatterConfig)().zone,o=(0,_formatConfig.configuredLocale)();if(o)return`${dateText(r,n)}, ${localeClock(r,o,n,e)}`;const i=wallClock(r,n);return withLabel(`${dateText(r,n)}, ${clockTime(i,hourCycleOf(e))}`,i,n,e.zoneLabel)};exports.formatDateTime=formatDateTime;const SECOND=1e3,MINUTE=6e4,HOUR=36e5,DAY=24*HOUR,WEEK=7*DAY,MONTH=30*DAY,YEAR=365*DAY,INTL_UNITS=[["year",YEAR],["month",MONTH],["day",DAY],["hour",HOUR],["minute",6e4]],formatRelative=(t,e={})=>{const r=toInstant(t),n=toInstant(e.now??Date.now());if(!r||!n)return emptyOf(e.empty);const o=r.getTime()-n.getTime(),i=Math.abs(o),a=Intl.RelativeTimeFormat,m=(0,_formatConfig.configuredLocale)();if((null!==m||!0===e.intl)&&"function"==typeof a){const t=(0,_intlCache.relativeTimeFormat)(a,m??(0,_formatConfig.getFormatterConfig)().locale),[e,r]=INTL_UNITS.find(([,t])=>i>=t)??["second",1e3];return t.format(Math.round(o/r),e)}if(i<6e4)return"just now";const[l,u]=i<HOUR?["minute",6e4]:i<DAY?["hour",HOUR]:i<WEEK?["day",DAY]:i<MONTH?["week",WEEK]:i<YEAR?["month",MONTH]:["year",YEAR],c=Math.floor(i/u),s=`${c} ${l}${1===c?"":"s"}`;return o<0?`${s} ago`:`in ${s}`};exports.formatRelative=formatRelative;const toNumber=t=>{if(null==t)return null;if("string"==typeof t&&""===t.trim())return null;const e="number"==typeof t?t:Number(t);return Number.isFinite(e)?e:null},clampDigits=t=>Math.min(20,Math.max(0,Math.trunc(t))),shiftDecimal=(t,e)=>/e/i.test(String(t))?t*10**e:Number(`${t}e${e}`),houseSeparators=()=>(0,_formatConfig.numberSeparators)()??{decimal:".",group:","},groupInteger=(t,e,r)=>{if("none"===e||t.length<=3)return t;if("international"===e)return t.replace(/\B(?=(\d{3})+(?!\d))/g,r);return`${t.slice(0,-3).replace(/\B(?=(\d{2})+(?!\d))/g,r)}${r}${t.slice(-3)}`},hasIntlNumber=()=>"undefined"!=typeof Intl&&"function"==typeof Intl.NumberFormat,plainDigits=(t,e)=>{if(hasIntlNumber())return(0,_intlCache.numberFormat)("en-US",{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:e}).format(t);const r=Math.min(e,15);return shiftDecimal(Math.round(shiftDecimal(t,r)),-r).toFixed(r)},decimalText=(t,e,r,n)=>{const o=Math.max(clampDigits(r),clampDigits(e)),i=clampDigits(e),a=plainDigits(Math.abs(t),o),[m="0",l=""]=a.split(".");let u=l.padEnd(i,"0");for(;u.length>i&&u.endsWith("0");)u=u.slice(0,-1);const c=houseSeparators(),s=groupInteger(m,n,c.group)+(u?`${c.decimal}${u}`:"");return t<0&&/[1-9]/.test(a)?`-${s}`:s},HOUSE_NUMBER_KEYS=new Set(["grouping","minimumFractionDigits","maximumFractionDigits","locale","empty","scale"]),intlNumberOptions=t=>{if(!Object.entries(t).some(([t,e])=>void 0!==e&&!HOUSE_NUMBER_KEYS.has(t)))return null;const{grouping:e,locale:r,empty:n,scale:o,...i}=t;return"none"===e&&void 0===i.useGrouping?{...i,useGrouping:!1}:i},localeOf=t=>t.locale??(0,_formatConfig.getFormatterConfig)().locale,intlTextLocale=t=>{const e=(0,_formatConfig.configuredLocale)();return null===e||"indian"===t.grouping||"international"===t.grouping?null:t.locale??e},fractionDigits=(t,e)=>{const r=clampDigits(t);return{minimumFractionDigits:r,maximumFractionDigits:Math.max(r,clampDigits(e))}},groupingOption=t=>"none"===t?{useGrouping:!1}:{},formatNumber=(t,e={})=>{const r=toNumber(t);if(null===r)return emptyOf(e.empty);const n=intlNumberOptions(e);if(n)return(0,_formatConfig.styledNumber)((0,_intlCache.numberFormat)(localeOf(e),n),r);const o=intlTextLocale(e);return o?(0,_formatConfig.styledNumber)((0,_intlCache.numberFormat)(o,{...fractionDigits(e.minimumFractionDigits??0,e.maximumFractionDigits??3),...groupingOption(e.grouping)}),r):decimalText(r,e.minimumFractionDigits??0,e.maximumFractionDigits??3,e.grouping??(0,_formatConfig.groupingForLocale)(localeOf(e)))};exports.formatNumber=formatNumber;const formatPercent=(t,e={})=>{const r=toNumber(t);if(null===r)return emptyOf(e.empty);const n=intlNumberOptions(e);if(n){const t="percent"===e.scale?shiftDecimal(r,-2):r;return(0,_formatConfig.styledNumber)((0,_intlCache.numberFormat)(localeOf(e),{style:"percent",...n}),t)}const o=intlTextLocale(e);if(o){const t="percent"===e.scale?shiftDecimal(r,-2):r;return(0,_formatConfig.styledNumber)((0,_intlCache.numberFormat)(o,{style:"percent",...fractionDigits(e.minimumFractionDigits??0,e.maximumFractionDigits??e.minimumFractionDigits??0),...groupingOption(e.grouping)}),t)}const i="percent"===e.scale?r:shiftDecimal(r,2);return`${decimalText(i,e.minimumFractionDigits??0,e.maximumFractionDigits??e.minimumFractionDigits??0,e.grouping??(0,_formatConfig.groupingForLocale)(localeOf(e)))}%`};exports.formatPercent=formatPercent;const SYMBOLS={INR:"₹",USD:"$",EUR:"€",GBP:"£"},MINOR_DIGITS={JPY:0,KRW:0,VND:0,BHD:3,JOD:3,KWD:3,OMR:3,TND:3},formatMinor=(t,e)=>{if(!e?.currency)throw new TypeError('formatMinor needs options.currency, an ISO 4217 code such as "INR".');const r=toNumber(t);if(null===r)return emptyOf(e.empty);const n=e.currency.toUpperCase(),o=MINOR_DIGITS[n]??2,i=Math.round(Math.abs(r)),a=String(i).padStart(o+1,"0"),m=a.slice(0,a.length-o);let l=a.slice(a.length-o);e.dropZeroDecimals&&/^0*$/.test(l)&&(l="");const u=intlTextLocale({grouping:e.grouping});if(u)try{const t=Number(`${r<0&&0!==i?"-":""}${m}.${a.slice(a.length-o)||"0"}`);return(0,_formatConfig.styledNumber)((0,_intlCache.numberFormat)(u,{...!1===e.symbol?{}:{style:"currency",currency:n},...fractionDigits(l?o:0,o),...groupingOption(e.grouping)}),t)}catch{}const c=e.grouping??("INR"===n?"indian":"international"),s=houseSeparators(),f=groupInteger(m,c,s.group)+(l?`${s.decimal}${l}`:""),g=r<0&&0!==i?"-":"";if(!1===e.symbol)return`${g}${f}`;const p=SYMBOLS[n];return p?`${g}${p}${f}`:`${g}${n} ${f}`};exports.formatMinor=formatMinor;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.formatTime=exports.formatRelative=exports.formatPercent=exports.formatNumber=exports.formatMinor=exports.formatDateTime=exports.formatDate=void 0;var _formatConfig=require("./formatConfig.js"),_intlCache=require("./intlCache.js");const MONTHS=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],IST_OFFSET_MINUTES=330,IST_NAMES=["IST","Asia/Kolkata","Asia/Calcutta"],DATE_ONLY=/^\d{4}-\d{2}-\d{2}$/,pad2=t=>t<10?`0${t}`:`${t}`,emptyOf=t=>t??(0,_formatConfig.getFormatterConfig)().empty,toInstant=t=>{if(null==t||""===t)return null;const e=t instanceof Date?t:new Date("string"==typeof t?t.trim():t);return Number.isNaN(e.getTime())?null:e},isDateOnly=t=>"string"==typeof t&&DATE_ONLY.test(t.trim()),gmtLabel=t=>{if(0===t)return"GMT";const e=t>0?"+":"-",r=Math.abs(t),n=r%60;return`GMT${e}${Math.floor(r/60)}${0===n?"":`:${pad2(n)}`}`},shifted=(t,e,r)=>{const n=new Date(t.getTime()+6e4*e);return{year:n.getUTCFullYear(),month:n.getUTCMonth(),day:n.getUTCDate(),hour:n.getUTCHours(),minute:n.getUTCMinutes(),label:r}},inIanaZone=(t,e)=>{const r=(0,_intlCache.dateTimeFormat)("en-US",{timeZone:e,year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",hour12:!1}).formatToParts(t),read=t=>Number.parseInt(r.find(e=>e.type===t)?.value??"",10),n=read("year"),o=read("month")-1,i=read("day"),a=read("hour")%24,m=read("minute"),l=Date.UTC(n,o,i,a,m),u=Math.round((l-6e4*Math.floor(t.getTime()/6e4))/6e4);return{year:n,month:o,day:i,hour:a,minute:m,label:gmtLabel(u)}},wallClock=(t,e)=>IST_NAMES.includes(e)?shifted(t,330,"IST"):"UTC"===e?shifted(t,0,"UTC"):"viewer"===e?{year:t.getFullYear(),month:t.getMonth(),day:t.getDate(),hour:t.getHours(),minute:t.getMinutes(),label:gmtLabel(-t.getTimezoneOffset())}:inIanaZone(t,e),hourCycleOf=t=>t.hourCycle??12,dayMonthYear=t=>`${pad2(t.day)}-${MONTHS[t.month]}-${t.year}`,numericDate=(t,e)=>{const r=pad2(t.day),n=pad2(t.month+1),o=String(t.year).padStart(4,"0");return"DayMonthYear"===e?`${r}/${n}/${o}`:"MonthDayYear"===e?`${n}/${r}/${o}`:`${o}-${n}-${r}`},clockTime=(t,e)=>24===e?`${pad2(t.hour)}:${pad2(t.minute)}`:`${t.hour%12||12}:${pad2(t.minute)} ${t.hour<12?"AM":"PM"}`,labelled=(t,e)=>e??!IST_NAMES.includes(t),withLabel=(t,e,r,n)=>labelled(r,n)?`${t} ${e.label}`:t,intlZone=t=>{if("viewer"!==t)return IST_NAMES.includes(t)?"Asia/Kolkata":t},localeDayMonthYear=(t,e,r)=>{const n=(0,_intlCache.dateTimeFormat)(e,{day:"2-digit",month:"short",year:"numeric",timeZone:r}).formatToParts(t),part=t=>n.find(e=>e.type===t)?.value??"";return`${part("day")}-${part("month").replace(".","")}-${part("year")}`},dateText=(t,e)=>{const r=(0,_formatConfig.getFormatterConfig)().dateOrder??"DayMonthNameYear";if("DayMonthNameYear"!==r)return numericDate(wallClock(t,e),r);const n=(0,_formatConfig.configuredLocale)();return n?localeDayMonthYear(t,n,intlZone(e)):dayMonthYear(wallClock(t,e))},localeClock=(t,e,r,n)=>(0,_intlCache.dateTimeFormat)(e,{hour:"2-digit",minute:"2-digit",timeZone:intlZone(r),timeZoneName:labelled(r,n.zoneLabel)?"short":void 0,hourCycle:void 0===n.hourCycle?void 0:24===n.hourCycle?"h23":"h12"}).format(t),formatDate=(t,e={})=>{const r=toInstant(t);return r?dateText(r,isDateOnly(t)?"UTC":e.zone??(0,_formatConfig.getFormatterConfig)().zone):emptyOf(e.empty)};exports.formatDate=formatDate;const formatTime=(t,e={})=>{const r=toInstant(t);if(!r)return emptyOf(e.empty);const n=e.zone??(0,_formatConfig.getFormatterConfig)().zone,o=(0,_formatConfig.configuredLocale)();if(o)return localeClock(r,o,n,e);const i=wallClock(r,n);return withLabel(clockTime(i,hourCycleOf(e)),i,n,e.zoneLabel)};exports.formatTime=formatTime;const formatDateTime=(t,e={})=>{const r=toInstant(t);if(!r)return emptyOf(e.empty);const n=e.zone??(0,_formatConfig.getFormatterConfig)().zone,o=(0,_formatConfig.configuredLocale)();if(o)return`${dateText(r,n)}, ${localeClock(r,o,n,e)}`;const i=wallClock(r,n);return withLabel(`${dateText(r,n)}, ${clockTime(i,hourCycleOf(e))}`,i,n,e.zoneLabel)};exports.formatDateTime=formatDateTime;const SECOND=1e3,MINUTE=6e4,HOUR=36e5,DAY=24*HOUR,WEEK=7*DAY,MONTH=30*DAY,YEAR=365*DAY,INTL_UNITS=[["year",YEAR],["month",MONTH],["day",DAY],["hour",HOUR],["minute",6e4]],formatRelative=(t,e={})=>{const r=toInstant(t),n=toInstant(e.now??Date.now());if(!r||!n)return emptyOf(e.empty);const o=r.getTime()-n.getTime(),i=Math.abs(o),a=Intl.RelativeTimeFormat,m=(0,_formatConfig.configuredLocale)();if((null!==m||!0===e.intl)&&"function"==typeof a){const t=(0,_intlCache.relativeTimeFormat)(a,m??(0,_formatConfig.getFormatterConfig)().locale),[e,r]=INTL_UNITS.find(([,t])=>i>=t)??["second",1e3];return t.format(Math.round(o/r),e)}if(i<6e4)return"just now";const[l,u]=i<HOUR?["minute",6e4]:i<DAY?["hour",HOUR]:i<WEEK?["day",DAY]:i<MONTH?["week",WEEK]:i<YEAR?["month",MONTH]:["year",YEAR],c=Math.floor(i/u),s=`${c} ${l}${1===c?"":"s"}`;return o<0?`${s} ago`:`in ${s}`};exports.formatRelative=formatRelative;const toNumber=t=>{if(null==t)return null;if("string"==typeof t&&""===t.trim())return null;const e="number"==typeof t?t:Number(t);return Number.isFinite(e)?e:null},clampDigits=t=>Math.min(20,Math.max(0,Math.trunc(t))),shiftDecimal=(t,e)=>/e/i.test(String(t))?t*10**e:Number(`${t}e${e}`),houseSeparators=()=>(0,_formatConfig.numberSeparators)()??{decimal:".",group:","},groupInteger=(t,e,r)=>{if("none"===e||t.length<=3)return t;if("international"===e)return t.replace(/\B(?=(\d{3})+(?!\d))/g,r);return`${t.slice(0,-3).replace(/\B(?=(\d{2})+(?!\d))/g,r)}${r}${t.slice(-3)}`},hasIntlNumber=()=>"undefined"!=typeof Intl&&"function"==typeof Intl.NumberFormat,plainDigits=(t,e)=>{if(hasIntlNumber())return(0,_intlCache.numberFormat)("en-US",{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:e}).format(t);const r=Math.min(e,15);return shiftDecimal(Math.round(shiftDecimal(t,r)),-r).toFixed(r)},decimalText=(t,e,r,n)=>{const o=Math.max(clampDigits(r),clampDigits(e)),i=clampDigits(e),a=plainDigits(Math.abs(t),o),[m="0",l=""]=a.split(".");let u=l.padEnd(i,"0");for(;u.length>i&&u.endsWith("0");)u=u.slice(0,-1);const c=houseSeparators(),s=groupInteger(m,n,c.group)+(u?`${c.decimal}${u}`:"");return t<0&&/[1-9]/.test(a)?`-${s}`:s},HOUSE_NUMBER_KEYS=new Set(["grouping","minimumFractionDigits","maximumFractionDigits","locale","empty","scale"]),intlNumberOptions=t=>{if(!Object.entries(t).some(([t,e])=>void 0!==e&&!HOUSE_NUMBER_KEYS.has(t)))return null;const{grouping:e,locale:r,empty:n,scale:o,...i}=t;return"none"===e&&void 0===i.useGrouping?{...i,useGrouping:!1}:i},localeOf=t=>t.locale??(0,_formatConfig.getFormatterConfig)().locale,intlTextLocale=t=>{const e=(0,_formatConfig.configuredLocale)();return null===e||"indian"===t.grouping||"international"===t.grouping?null:t.locale??e},fractionDigits=(t,e)=>{const r=clampDigits(t);return{minimumFractionDigits:r,maximumFractionDigits:Math.max(r,clampDigits(e))}},groupingOption=t=>"none"===t?{useGrouping:!1}:{},formatNumber=(t,e={})=>{const r=toNumber(t);if(null===r)return emptyOf(e.empty);const n=intlNumberOptions(e);if(n)return(0,_formatConfig.styledNumber)((0,_intlCache.numberFormat)(localeOf(e),n),r);const o=intlTextLocale(e);return o?(0,_formatConfig.styledNumber)((0,_intlCache.numberFormat)(o,{...fractionDigits(e.minimumFractionDigits??0,e.maximumFractionDigits??3),...groupingOption(e.grouping)}),r):decimalText(r,e.minimumFractionDigits??0,e.maximumFractionDigits??3,e.grouping??(0,_formatConfig.groupingForLocale)(localeOf(e)))};exports.formatNumber=formatNumber;const formatPercent=(t,e={})=>{const r=toNumber(t);if(null===r)return emptyOf(e.empty);const n=intlNumberOptions(e);if(n){const t="percent"===e.scale?shiftDecimal(r,-2):r;return(0,_formatConfig.styledNumber)((0,_intlCache.numberFormat)(localeOf(e),{style:"percent",...n}),t)}const o=intlTextLocale(e);if(o){const t="percent"===e.scale?shiftDecimal(r,-2):r;return(0,_formatConfig.styledNumber)((0,_intlCache.numberFormat)(o,{style:"percent",...fractionDigits(e.minimumFractionDigits??0,e.maximumFractionDigits??e.minimumFractionDigits??0),...groupingOption(e.grouping)}),t)}const i="percent"===e.scale?r:shiftDecimal(r,2);return`${decimalText(i,e.minimumFractionDigits??0,e.maximumFractionDigits??e.minimumFractionDigits??0,e.grouping??(0,_formatConfig.groupingForLocale)(localeOf(e)))}%`};exports.formatPercent=formatPercent;const SYMBOLS={INR:"₹",USD:"$",EUR:"€",GBP:"£"},MINOR_DIGITS={JPY:0,KRW:0,VND:0,BHD:3,JOD:3,KWD:3,OMR:3,TND:3},formatMinor=(t,e)=>{if(!e?.currency)throw new TypeError('formatMinor needs options.currency, an ISO 4217 code such as "INR".');const r=toNumber(t);if(null===r)return emptyOf(e.empty);const n=e.currency.toUpperCase(),o=MINOR_DIGITS[n]??2,i=Math.round(Math.abs(r)),a=String(i).padStart(o+1,"0"),m=a.slice(0,a.length-o);let l=a.slice(a.length-o);e.dropZeroDecimals&&/^0*$/.test(l)&&(l="");const u=intlTextLocale({grouping:e.grouping});if(u)try{const t=Number(`${r<0&&0!==i?"-":""}${m}.${a.slice(a.length-o)||"0"}`);return(0,_formatConfig.styledNumber)((0,_intlCache.numberFormat)(u,{...!1===e.symbol?{}:{style:"currency",currency:n},...fractionDigits(l?o:0,o),...groupingOption(e.grouping)}),t)}catch(t){if(t instanceof RangeError)throw new RangeError(`formatMinor rejected currency "${n}" or locale "${u}": ${t.message}`,{cause:t});throw t}const c=e.grouping??("INR"===n?"indian":"international"),s=houseSeparators(),f=groupInteger(m,c,s.group)+(l?`${s.decimal}${l}`:""),g=r<0&&0!==i?"-":"";if(!1===e.symbol)return`${g}${f}`;const p=SYMBOLS[n];return p?`${g}${p}${f}`:`${g}${n} ${f}`};exports.formatMinor=formatMinor;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.formatCompactNumber=void 0,exports.formatNumber=formatNumber,exports.formatPercent=formatPercent;var _formatConfig=require("./formatConfig.js"),_house=require("./house.js"),_intlCache=require("./intlCache.js");const hasIntlNumber=()=>"undefined"!=typeof Intl&&"function"==typeof Intl.NumberFormat,withDecimalMark=
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.formatCompactNumber=void 0,exports.formatNumber=formatNumber,exports.formatPercent=formatPercent;var _formatConfig=require("./formatConfig.js"),_house=require("./house.js"),_intlCache=require("./intlCache.js");const hasIntlNumber=()=>"undefined"!=typeof Intl&&"function"==typeof Intl.NumberFormat,withDecimalMark=e=>{const r=(0,_formatConfig.numberSeparators)();return null===r?e:e.replace(".",r.decimal)};function formatNumber(e,r,t){if("number"!=typeof r&&void 0===t)return(0,_house.formatNumber)(e,r);const o="number"==typeof r?r:void 0,i=e;if(null==i||Number.isNaN(i))return"";if(hasIntlNumber())try{const e={};return null!=o&&(e.minimumFractionDigits=o,e.maximumFractionDigits=o),(0,_formatConfig.styledNumber)((0,_intlCache.numberFormat)(t??"en-IN",e),i)}catch(e){if(e instanceof RangeError)throw new RangeError(`[@webority/mobile-core] formatNumber rejected locale "${t??"en-IN"}" or fraction digits ${o}: ${e.message}`,{cause:e});throw e}return withDecimalMark(null!=o?i.toFixed(o):String(i))}function formatPercent(e,r,t,o){if("number"!=typeof r&&void 0===t&&void 0===o)return(0,_house.formatPercent)(e,r);const i="number"==typeof r?r:0,n=e;if(null==n||Number.isNaN(n))return"";const a=t??1?n:n/100;if(hasIntlNumber())try{return(0,_formatConfig.styledNumber)((0,_intlCache.numberFormat)(o??"en-IN",{style:"percent",minimumFractionDigits:i,maximumFractionDigits:i}),a)}catch(e){if(e instanceof RangeError)throw new RangeError(`[@webority/mobile-core] formatPercent rejected locale "${o??"en-IN"}" or fraction digits ${i}: ${e.message}`,{cause:e});throw e}return`${withDecimalMark((100*a).toFixed(i))}%`}const formatCompactNumber=(e,r="en-IN")=>{if(null==e||Number.isNaN(e))return"";if(hasIntlNumber())try{return(0,_formatConfig.styledNumber)((0,_intlCache.numberFormat)(r,{notation:"compact",maximumFractionDigits:1}),e)}catch(e){if(e instanceof RangeError)throw new RangeError(`[@webority/mobile-core] formatCompactNumber rejected locale "${r}": ${e.message}`,{cause:e});throw e}const t=Math.abs(e),o=e<0?"-":"";return t>=1e7?`${o}${withDecimalMark((t/1e7).toFixed(1))}Cr`:t>=1e5?`${o}${withDecimalMark((t/1e5).toFixed(1))}L`:t>=1e3?`${o}${withDecimalMark((t/1e3).toFixed(1))}K`:withDecimalMark(`${e}`)};exports.formatCompactNumber=formatCompactNumber;
|
|
@@ -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{}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.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 +1 @@
|
|
|
1
|
-
"use strict";import{configuredLocale,getFormatterConfig,isFormatterConfigured,numberSeparators,styledNumber}from"./formatConfig.js";import{numberFormat}from"./intlCache.js";const hasIntlNumber=()=>"undefined"!=typeof Intl&&"function"==typeof Intl.NumberFormat,indianGroupingFallback=(r,e)=>{const{decimal:t,group:n}=numberSeparators()??{decimal:".",group:","},
|
|
1
|
+
"use strict";import{configuredLocale,getFormatterConfig,isFormatterConfigured,numberSeparators,styledNumber}from"./formatConfig.js";import{numberFormat}from"./intlCache.js";const hasIntlNumber=()=>"undefined"!=typeof Intl&&"function"==typeof Intl.NumberFormat,indianGroupingFallback=(r,e)=>{const{decimal:t,group:n}=numberSeparators()??{decimal:".",group:","},o=r<0?"-":"",i=Math.abs(r).toFixed(e),[c,m]=i.split("."),u=c.length>3?c.slice(-3):c,a=c.length>3?c.slice(0,-3):"";return o+(a?a.replace(/\B(?=(\d{2})+(?!\d))/g,n)+n+u:u)+(m?`${t}${m}`:"")},toAmount=r=>{if(null==r||"string"==typeof r&&""===r.trim())return null;const e="number"==typeof r?r:Number(r);return Number.isFinite(e)?e:null},currencyDigits=(r,e)=>numberFormat(r,{style:"currency",currency:e}).resolvedOptions().maximumFractionDigits??2;export const formatCurrency=(r,e)=>{if(!e?.currency)throw new TypeError('[@webority/mobile-core] formatCurrency needs options.currency, an ISO 4217 code such as "INR".');const{currency:t,locale:n=configuredLocale()??"en-IN",minimumFractionDigits:o,maximumFractionDigits:i,stripSymbol:c=!1,empty:m=(isFormatterConfigured("locale")||isFormatterConfigured("empty")?getFormatterConfig().empty:""),...u}=e,a=toAmount(r);if(null===a)return m;if(hasIntlNumber())try{const r=i??currencyDigits(n,t),e=o??(Number.isInteger(a)?0:r),m=styledNumber(numberFormat(n,{...u,style:"currency",currency:t,minimumFractionDigits:e,maximumFractionDigits:Math.max(e,r)}),a);return c?m.replace(/[^\d,.\s\-+]/g,"").trim():m}catch(r){if(r instanceof RangeError)throw new RangeError(`[@webority/mobile-core] formatCurrency rejected currency "${t}" or locale "${n}": ${r.message}`,{cause:r});throw r}const s=indianGroupingFallback(a,o??(Number.isInteger(a)?0:2));return c?s:"INR"===t?`₹${s}`:`${t} ${s}`};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{formatDate as houseDate,formatDateTime as houseDateTime,formatTime as houseTime}from"./house.js";import{dateTimeFormat,relativeTimeFormat}from"./intlCache.js";const toDate=
|
|
1
|
+
"use strict";import{formatDate as houseDate,formatDateTime as houseDateTime,formatTime as houseTime}from"./house.js";import{dateTimeFormat,relativeTimeFormat}from"./intlCache.js";const toDate=e=>{if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;const t=new Date(e);return Number.isNaN(t.getTime())?null:t},hasIntl=()=>"undefined"!=typeof Intl&&"function"==typeof Intl.DateTimeFormat,PAD=e=>e<10?`0${e}`:`${e}`,fallbackDate=(e,t)=>{const r=PAD(e.getDate()),a=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][e.getMonth()],o=["January","February","March","April","May","June","July","August","September","October","November","December"][e.getMonth()],n=e.getFullYear(),i=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][e.getDay()];switch(t){case"short":return`${r}/${PAD(e.getMonth()+1)}/${n}`;case"long":return`${r} ${o} ${n}`;case"full":return`${i}, ${r} ${o} ${n}`;default:return`${r} ${a} ${n}`}},fallbackTime=(e,t)=>{const r=PAD(e.getHours()),a=PAD(e.getMinutes());if("short"===t)return`${r}:${a}`;return`${r}:${a}:${PAD(e.getSeconds())}`},isStyle=e=>"string"==typeof e;export function formatDate(e,t,r="en-IN"){if(!isStyle(t))return houseDate(e,t);const a=t,o=toDate(e);if(!o)return"";if(hasIntl())try{return dateTimeFormat(r,{dateStyle:a}).format(o)}catch(e){if(e instanceof RangeError)throw new RangeError(`[@webority/mobile-core] formatDate rejected style "${a}" or locale "${r}": ${e.message}`,{cause:e});throw e}return fallbackDate(o,a)}export function formatTime(e,t,r="en-IN"){if(!isStyle(t))return houseTime(e,t);const a=t,o=toDate(e);if(!o)return"";if(hasIntl())try{return dateTimeFormat(r,{timeStyle:a}).format(o)}catch(e){if(e instanceof RangeError)throw new RangeError(`[@webority/mobile-core] formatTime rejected style "${a}" or locale "${r}": ${e.message}`,{cause:e});throw e}return fallbackTime(o,a)}export function formatDateTime(e,t,r="short",a="en-IN"){if(!isStyle(t))return houseDateTime(e,t);const o=t,n=toDate(e);if(!n)return"";if(hasIntl())try{return dateTimeFormat(a,{dateStyle:o,timeStyle:r}).format(n)}catch(e){if(e instanceof RangeError)throw new RangeError(`[@webority/mobile-core] formatDateTime rejected styles "${o}"/"${r}" or locale "${a}": ${e.message}`,{cause:e});throw e}return`${fallbackDate(n,o)}, ${fallbackTime(n,r)}`}const SECOND=1e3,MINUTE=6e4,HOUR=36e5,DAY=24*HOUR,WEEK=7*DAY,MONTH=30*DAY,YEAR=365*DAY;export const formatRelativeTime=(e,t=new Date,r="en-IN")=>{const a=toDate(e),o=toDate(t);if(!a||!o)return"";const n=a.getTime()-o.getTime(),i=Math.abs(n);let s,u;i<6e4?(s="second",u=Math.round(n/1e3)):i<HOUR?(s="minute",u=Math.round(n/6e4)):i<DAY?(s="hour",u=Math.round(n/HOUR)):i<WEEK?(s="day",u=Math.round(n/DAY)):i<MONTH?(s="week",u=Math.round(n/WEEK)):i<YEAR?(s="month",u=Math.round(n/MONTH)):(s="year",u=Math.round(n/YEAR));const m=hasIntl()?Intl.RelativeTimeFormat:void 0;if("function"==typeof m)try{return relativeTimeFormat(m,r).format(u,s)}catch(e){if(e instanceof RangeError)throw new RangeError(`[@webority/mobile-core] formatRelativeTime rejected locale "${r}": ${e.message}`,{cause:e});throw e}const c=u<0,l=Math.abs(u),f=1===l?s:`${s}s`;return c?`${l} ${f} ago`:`in ${l} ${f}`};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{configuredLocale,getFormatterConfig,groupingForLocale,numberSeparators,styledNumber}from"./formatConfig.js";import{dateTimeFormat,numberFormat,relativeTimeFormat}from"./intlCache.js";const MONTHS=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],IST_OFFSET_MINUTES=330,IST_NAMES=["IST","Asia/Kolkata","Asia/Calcutta"],DATE_ONLY=/^\d{4}-\d{2}-\d{2}$/,pad2=t=>t<10?`0${t}`:`${t}`,emptyOf=t=>t??getFormatterConfig().empty,toInstant=t=>{if(null==t||""===t)return null;const e=t instanceof Date?t:new Date("string"==typeof t?t.trim():t);return Number.isNaN(e.getTime())?null:e},isDateOnly=t=>"string"==typeof t&&DATE_ONLY.test(t.trim()),gmtLabel=t=>{if(0===t)return"GMT";const e=t>0?"+":"-",n=Math.abs(t),r=n%60;return`GMT${e}${Math.floor(n/60)}${0===r?"":`:${pad2(r)}`}`},shifted=(t,e,n)=>{const r=new Date(t.getTime()+6e4*e);return{year:r.getUTCFullYear(),month:r.getUTCMonth(),day:r.getUTCDate(),hour:r.getUTCHours(),minute:r.getUTCMinutes(),label:n}},inIanaZone=(t,e)=>{const n=dateTimeFormat("en-US",{timeZone:e,year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",hour12:!1}).formatToParts(t),read=t=>Number.parseInt(n.find(e=>e.type===t)?.value??"",10),r=read("year"),o=read("month")-1,i=read("day"),a=read("hour")%24,m=read("minute"),l=Date.UTC(r,o,i,a,m),u=Math.round((l-6e4*Math.floor(t.getTime()/6e4))/6e4);return{year:r,month:o,day:i,hour:a,minute:m,label:gmtLabel(u)}},wallClock=(t,e)=>IST_NAMES.includes(e)?shifted(t,330,"IST"):"UTC"===e?shifted(t,0,"UTC"):"viewer"===e?{year:t.getFullYear(),month:t.getMonth(),day:t.getDate(),hour:t.getHours(),minute:t.getMinutes(),label:gmtLabel(-t.getTimezoneOffset())}:inIanaZone(t,e),hourCycleOf=t=>t.hourCycle??12,dayMonthYear=t=>`${pad2(t.day)}-${MONTHS[t.month]}-${t.year}`,numericDate=(t,e)=>{const n=pad2(t.day),r=pad2(t.month+1),o=String(t.year).padStart(4,"0");return"DayMonthYear"===e?`${n}/${r}/${o}`:"MonthDayYear"===e?`${r}/${n}/${o}`:`${o}-${r}-${n}`},clockTime=(t,e)=>24===e?`${pad2(t.hour)}:${pad2(t.minute)}`:`${t.hour%12||12}:${pad2(t.minute)} ${t.hour<12?"AM":"PM"}`,labelled=(t,e)=>e??!IST_NAMES.includes(t),withLabel=(t,e,n,r)=>labelled(n,r)?`${t} ${e.label}`:t,intlZone=t=>{if("viewer"!==t)return IST_NAMES.includes(t)?"Asia/Kolkata":t},localeDayMonthYear=(t,e,n)=>{const r=dateTimeFormat(e,{day:"2-digit",month:"short",year:"numeric",timeZone:n}).formatToParts(t),part=t=>r.find(e=>e.type===t)?.value??"";return`${part("day")}-${part("month").replace(".","")}-${part("year")}`},dateText=(t,e)=>{const n=getFormatterConfig().dateOrder??"DayMonthNameYear";if("DayMonthNameYear"!==n)return numericDate(wallClock(t,e),n);const r=configuredLocale();return r?localeDayMonthYear(t,r,intlZone(e)):dayMonthYear(wallClock(t,e))},localeClock=(t,e,n,r)=>dateTimeFormat(e,{hour:"2-digit",minute:"2-digit",timeZone:intlZone(n),timeZoneName:labelled(n,r.zoneLabel)?"short":void 0,hourCycle:void 0===r.hourCycle?void 0:24===r.hourCycle?"h23":"h12"}).format(t);export const formatDate=(t,e={})=>{const n=toInstant(t);return n?dateText(n,isDateOnly(t)?"UTC":e.zone??getFormatterConfig().zone):emptyOf(e.empty)};export const formatTime=(t,e={})=>{const n=toInstant(t);if(!n)return emptyOf(e.empty);const r=e.zone??getFormatterConfig().zone,o=configuredLocale();if(o)return localeClock(n,o,r,e);const i=wallClock(n,r);return withLabel(clockTime(i,hourCycleOf(e)),i,r,e.zoneLabel)};export const formatDateTime=(t,e={})=>{const n=toInstant(t);if(!n)return emptyOf(e.empty);const r=e.zone??getFormatterConfig().zone,o=configuredLocale();if(o)return`${dateText(n,r)}, ${localeClock(n,o,r,e)}`;const i=wallClock(n,r);return withLabel(`${dateText(n,r)}, ${clockTime(i,hourCycleOf(e))}`,i,r,e.zoneLabel)};const SECOND=1e3,MINUTE=6e4,HOUR=36e5,DAY=24*HOUR,WEEK=7*DAY,MONTH=30*DAY,YEAR=365*DAY,INTL_UNITS=[["year",YEAR],["month",MONTH],["day",DAY],["hour",HOUR],["minute",6e4]];export const formatRelative=(t,e={})=>{const n=toInstant(t),r=toInstant(e.now??Date.now());if(!n||!r)return emptyOf(e.empty);const o=n.getTime()-r.getTime(),i=Math.abs(o),a=Intl.RelativeTimeFormat,m=configuredLocale();if((null!==m||!0===e.intl)&&"function"==typeof a){const t=relativeTimeFormat(a,m??getFormatterConfig().locale),[e,n]=INTL_UNITS.find(([,t])=>i>=t)??["second",1e3];return t.format(Math.round(o/n),e)}if(i<6e4)return"just now";const[l,u]=i<HOUR?["minute",6e4]:i<DAY?["hour",HOUR]:i<WEEK?["day",DAY]:i<MONTH?["week",WEEK]:i<YEAR?["month",MONTH]:["year",YEAR],c=Math.floor(i/u),s=`${c} ${l}${1===c?"":"s"}`;return o<0?`${s} ago`:`in ${s}`};const toNumber=t=>{if(null==t)return null;if("string"==typeof t&&""===t.trim())return null;const e="number"==typeof t?t:Number(t);return Number.isFinite(e)?e:null},clampDigits=t=>Math.min(20,Math.max(0,Math.trunc(t))),shiftDecimal=(t,e)=>/e/i.test(String(t))?t*10**e:Number(`${t}e${e}`),houseSeparators=()=>numberSeparators()??{decimal:".",group:","},groupInteger=(t,e,n)=>{if("none"===e||t.length<=3)return t;if("international"===e)return t.replace(/\B(?=(\d{3})+(?!\d))/g,n);return`${t.slice(0,-3).replace(/\B(?=(\d{2})+(?!\d))/g,n)}${n}${t.slice(-3)}`},hasIntlNumber=()=>"undefined"!=typeof Intl&&"function"==typeof Intl.NumberFormat,plainDigits=(t,e)=>{if(hasIntlNumber())return numberFormat("en-US",{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:e}).format(t);const n=Math.min(e,15);return shiftDecimal(Math.round(shiftDecimal(t,n)),-n).toFixed(n)},decimalText=(t,e,n,r)=>{const o=Math.max(clampDigits(n),clampDigits(e)),i=clampDigits(e),a=plainDigits(Math.abs(t),o),[m="0",l=""]=a.split(".");let u=l.padEnd(i,"0");for(;u.length>i&&u.endsWith("0");)u=u.slice(0,-1);const c=houseSeparators(),s=groupInteger(m,r,c.group)+(u?`${c.decimal}${u}`:"");return t<0&&/[1-9]/.test(a)?`-${s}`:s},HOUSE_NUMBER_KEYS=new Set(["grouping","minimumFractionDigits","maximumFractionDigits","locale","empty","scale"]),intlNumberOptions=t=>{if(!Object.entries(t).some(([t,e])=>void 0!==e&&!HOUSE_NUMBER_KEYS.has(t)))return null;const{grouping:e,locale:n,empty:r,scale:o,...i}=t;return"none"===e&&void 0===i.useGrouping?{...i,useGrouping:!1}:i},localeOf=t=>t.locale??getFormatterConfig().locale,intlTextLocale=t=>{const e=configuredLocale();return null===e||"indian"===t.grouping||"international"===t.grouping?null:t.locale??e},fractionDigits=(t,e)=>{const n=clampDigits(t);return{minimumFractionDigits:n,maximumFractionDigits:Math.max(n,clampDigits(e))}},groupingOption=t=>"none"===t?{useGrouping:!1}:{};export const formatNumber=(t,e={})=>{const n=toNumber(t);if(null===n)return emptyOf(e.empty);const r=intlNumberOptions(e);if(r)return styledNumber(numberFormat(localeOf(e),r),n);const o=intlTextLocale(e);return o?styledNumber(numberFormat(o,{...fractionDigits(e.minimumFractionDigits??0,e.maximumFractionDigits??3),...groupingOption(e.grouping)}),n):decimalText(n,e.minimumFractionDigits??0,e.maximumFractionDigits??3,e.grouping??groupingForLocale(localeOf(e)))};export const formatPercent=(t,e={})=>{const n=toNumber(t);if(null===n)return emptyOf(e.empty);const r=intlNumberOptions(e);if(r){const t="percent"===e.scale?shiftDecimal(n,-2):n;return styledNumber(numberFormat(localeOf(e),{style:"percent",...r}),t)}const o=intlTextLocale(e);if(o){const t="percent"===e.scale?shiftDecimal(n,-2):n;return styledNumber(numberFormat(o,{style:"percent",...fractionDigits(e.minimumFractionDigits??0,e.maximumFractionDigits??e.minimumFractionDigits??0),...groupingOption(e.grouping)}),t)}const i="percent"===e.scale?n:shiftDecimal(n,2);return`${decimalText(i,e.minimumFractionDigits??0,e.maximumFractionDigits??e.minimumFractionDigits??0,e.grouping??groupingForLocale(localeOf(e)))}%`};const SYMBOLS={INR:"₹",USD:"$",EUR:"€",GBP:"£"},MINOR_DIGITS={JPY:0,KRW:0,VND:0,BHD:3,JOD:3,KWD:3,OMR:3,TND:3};export const formatMinor=(t,e)=>{if(!e?.currency)throw new TypeError('formatMinor needs options.currency, an ISO 4217 code such as "INR".');const n=toNumber(t);if(null===n)return emptyOf(e.empty);const r=e.currency.toUpperCase(),o=MINOR_DIGITS[r]??2,i=Math.round(Math.abs(n)),a=String(i).padStart(o+1,"0"),m=a.slice(0,a.length-o);let l=a.slice(a.length-o);e.dropZeroDecimals&&/^0*$/.test(l)&&(l="");const u=intlTextLocale({grouping:e.grouping});if(u)try{const t=Number(`${n<0&&0!==i?"-":""}${m}.${a.slice(a.length-o)||"0"}`);return styledNumber(numberFormat(u,{...!1===e.symbol?{}:{style:"currency",currency:r},...fractionDigits(l?o:0,o),...groupingOption(e.grouping)}),t)}catch{}const c=e.grouping??("INR"===r?"indian":"international"),s=houseSeparators(),g=groupInteger(m,c,s.group)+(l?`${s.decimal}${l}`:""),p=n<0&&0!==i?"-":"";if(!1===e.symbol)return`${p}${g}`;const f=SYMBOLS[r];return f?`${p}${f}${g}`:`${p}${r} ${g}`};
|
|
1
|
+
"use strict";import{configuredLocale,getFormatterConfig,groupingForLocale,numberSeparators,styledNumber}from"./formatConfig.js";import{dateTimeFormat,numberFormat,relativeTimeFormat}from"./intlCache.js";const MONTHS=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],IST_OFFSET_MINUTES=330,IST_NAMES=["IST","Asia/Kolkata","Asia/Calcutta"],DATE_ONLY=/^\d{4}-\d{2}-\d{2}$/,pad2=t=>t<10?`0${t}`:`${t}`,emptyOf=t=>t??getFormatterConfig().empty,toInstant=t=>{if(null==t||""===t)return null;const e=t instanceof Date?t:new Date("string"==typeof t?t.trim():t);return Number.isNaN(e.getTime())?null:e},isDateOnly=t=>"string"==typeof t&&DATE_ONLY.test(t.trim()),gmtLabel=t=>{if(0===t)return"GMT";const e=t>0?"+":"-",n=Math.abs(t),r=n%60;return`GMT${e}${Math.floor(n/60)}${0===r?"":`:${pad2(r)}`}`},shifted=(t,e,n)=>{const r=new Date(t.getTime()+6e4*e);return{year:r.getUTCFullYear(),month:r.getUTCMonth(),day:r.getUTCDate(),hour:r.getUTCHours(),minute:r.getUTCMinutes(),label:n}},inIanaZone=(t,e)=>{const n=dateTimeFormat("en-US",{timeZone:e,year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",hour12:!1}).formatToParts(t),read=t=>Number.parseInt(n.find(e=>e.type===t)?.value??"",10),r=read("year"),o=read("month")-1,i=read("day"),a=read("hour")%24,m=read("minute"),l=Date.UTC(r,o,i,a,m),u=Math.round((l-6e4*Math.floor(t.getTime()/6e4))/6e4);return{year:r,month:o,day:i,hour:a,minute:m,label:gmtLabel(u)}},wallClock=(t,e)=>IST_NAMES.includes(e)?shifted(t,330,"IST"):"UTC"===e?shifted(t,0,"UTC"):"viewer"===e?{year:t.getFullYear(),month:t.getMonth(),day:t.getDate(),hour:t.getHours(),minute:t.getMinutes(),label:gmtLabel(-t.getTimezoneOffset())}:inIanaZone(t,e),hourCycleOf=t=>t.hourCycle??12,dayMonthYear=t=>`${pad2(t.day)}-${MONTHS[t.month]}-${t.year}`,numericDate=(t,e)=>{const n=pad2(t.day),r=pad2(t.month+1),o=String(t.year).padStart(4,"0");return"DayMonthYear"===e?`${n}/${r}/${o}`:"MonthDayYear"===e?`${r}/${n}/${o}`:`${o}-${r}-${n}`},clockTime=(t,e)=>24===e?`${pad2(t.hour)}:${pad2(t.minute)}`:`${t.hour%12||12}:${pad2(t.minute)} ${t.hour<12?"AM":"PM"}`,labelled=(t,e)=>e??!IST_NAMES.includes(t),withLabel=(t,e,n,r)=>labelled(n,r)?`${t} ${e.label}`:t,intlZone=t=>{if("viewer"!==t)return IST_NAMES.includes(t)?"Asia/Kolkata":t},localeDayMonthYear=(t,e,n)=>{const r=dateTimeFormat(e,{day:"2-digit",month:"short",year:"numeric",timeZone:n}).formatToParts(t),part=t=>r.find(e=>e.type===t)?.value??"";return`${part("day")}-${part("month").replace(".","")}-${part("year")}`},dateText=(t,e)=>{const n=getFormatterConfig().dateOrder??"DayMonthNameYear";if("DayMonthNameYear"!==n)return numericDate(wallClock(t,e),n);const r=configuredLocale();return r?localeDayMonthYear(t,r,intlZone(e)):dayMonthYear(wallClock(t,e))},localeClock=(t,e,n,r)=>dateTimeFormat(e,{hour:"2-digit",minute:"2-digit",timeZone:intlZone(n),timeZoneName:labelled(n,r.zoneLabel)?"short":void 0,hourCycle:void 0===r.hourCycle?void 0:24===r.hourCycle?"h23":"h12"}).format(t);export const formatDate=(t,e={})=>{const n=toInstant(t);return n?dateText(n,isDateOnly(t)?"UTC":e.zone??getFormatterConfig().zone):emptyOf(e.empty)};export const formatTime=(t,e={})=>{const n=toInstant(t);if(!n)return emptyOf(e.empty);const r=e.zone??getFormatterConfig().zone,o=configuredLocale();if(o)return localeClock(n,o,r,e);const i=wallClock(n,r);return withLabel(clockTime(i,hourCycleOf(e)),i,r,e.zoneLabel)};export const formatDateTime=(t,e={})=>{const n=toInstant(t);if(!n)return emptyOf(e.empty);const r=e.zone??getFormatterConfig().zone,o=configuredLocale();if(o)return`${dateText(n,r)}, ${localeClock(n,o,r,e)}`;const i=wallClock(n,r);return withLabel(`${dateText(n,r)}, ${clockTime(i,hourCycleOf(e))}`,i,r,e.zoneLabel)};const SECOND=1e3,MINUTE=6e4,HOUR=36e5,DAY=24*HOUR,WEEK=7*DAY,MONTH=30*DAY,YEAR=365*DAY,INTL_UNITS=[["year",YEAR],["month",MONTH],["day",DAY],["hour",HOUR],["minute",6e4]];export const formatRelative=(t,e={})=>{const n=toInstant(t),r=toInstant(e.now??Date.now());if(!n||!r)return emptyOf(e.empty);const o=n.getTime()-r.getTime(),i=Math.abs(o),a=Intl.RelativeTimeFormat,m=configuredLocale();if((null!==m||!0===e.intl)&&"function"==typeof a){const t=relativeTimeFormat(a,m??getFormatterConfig().locale),[e,n]=INTL_UNITS.find(([,t])=>i>=t)??["second",1e3];return t.format(Math.round(o/n),e)}if(i<6e4)return"just now";const[l,u]=i<HOUR?["minute",6e4]:i<DAY?["hour",HOUR]:i<WEEK?["day",DAY]:i<MONTH?["week",WEEK]:i<YEAR?["month",MONTH]:["year",YEAR],c=Math.floor(i/u),s=`${c} ${l}${1===c?"":"s"}`;return o<0?`${s} ago`:`in ${s}`};const toNumber=t=>{if(null==t)return null;if("string"==typeof t&&""===t.trim())return null;const e="number"==typeof t?t:Number(t);return Number.isFinite(e)?e:null},clampDigits=t=>Math.min(20,Math.max(0,Math.trunc(t))),shiftDecimal=(t,e)=>/e/i.test(String(t))?t*10**e:Number(`${t}e${e}`),houseSeparators=()=>numberSeparators()??{decimal:".",group:","},groupInteger=(t,e,n)=>{if("none"===e||t.length<=3)return t;if("international"===e)return t.replace(/\B(?=(\d{3})+(?!\d))/g,n);return`${t.slice(0,-3).replace(/\B(?=(\d{2})+(?!\d))/g,n)}${n}${t.slice(-3)}`},hasIntlNumber=()=>"undefined"!=typeof Intl&&"function"==typeof Intl.NumberFormat,plainDigits=(t,e)=>{if(hasIntlNumber())return numberFormat("en-US",{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:e}).format(t);const n=Math.min(e,15);return shiftDecimal(Math.round(shiftDecimal(t,n)),-n).toFixed(n)},decimalText=(t,e,n,r)=>{const o=Math.max(clampDigits(n),clampDigits(e)),i=clampDigits(e),a=plainDigits(Math.abs(t),o),[m="0",l=""]=a.split(".");let u=l.padEnd(i,"0");for(;u.length>i&&u.endsWith("0");)u=u.slice(0,-1);const c=houseSeparators(),s=groupInteger(m,r,c.group)+(u?`${c.decimal}${u}`:"");return t<0&&/[1-9]/.test(a)?`-${s}`:s},HOUSE_NUMBER_KEYS=new Set(["grouping","minimumFractionDigits","maximumFractionDigits","locale","empty","scale"]),intlNumberOptions=t=>{if(!Object.entries(t).some(([t,e])=>void 0!==e&&!HOUSE_NUMBER_KEYS.has(t)))return null;const{grouping:e,locale:n,empty:r,scale:o,...i}=t;return"none"===e&&void 0===i.useGrouping?{...i,useGrouping:!1}:i},localeOf=t=>t.locale??getFormatterConfig().locale,intlTextLocale=t=>{const e=configuredLocale();return null===e||"indian"===t.grouping||"international"===t.grouping?null:t.locale??e},fractionDigits=(t,e)=>{const n=clampDigits(t);return{minimumFractionDigits:n,maximumFractionDigits:Math.max(n,clampDigits(e))}},groupingOption=t=>"none"===t?{useGrouping:!1}:{};export const formatNumber=(t,e={})=>{const n=toNumber(t);if(null===n)return emptyOf(e.empty);const r=intlNumberOptions(e);if(r)return styledNumber(numberFormat(localeOf(e),r),n);const o=intlTextLocale(e);return o?styledNumber(numberFormat(o,{...fractionDigits(e.minimumFractionDigits??0,e.maximumFractionDigits??3),...groupingOption(e.grouping)}),n):decimalText(n,e.minimumFractionDigits??0,e.maximumFractionDigits??3,e.grouping??groupingForLocale(localeOf(e)))};export const formatPercent=(t,e={})=>{const n=toNumber(t);if(null===n)return emptyOf(e.empty);const r=intlNumberOptions(e);if(r){const t="percent"===e.scale?shiftDecimal(n,-2):n;return styledNumber(numberFormat(localeOf(e),{style:"percent",...r}),t)}const o=intlTextLocale(e);if(o){const t="percent"===e.scale?shiftDecimal(n,-2):n;return styledNumber(numberFormat(o,{style:"percent",...fractionDigits(e.minimumFractionDigits??0,e.maximumFractionDigits??e.minimumFractionDigits??0),...groupingOption(e.grouping)}),t)}const i="percent"===e.scale?n:shiftDecimal(n,2);return`${decimalText(i,e.minimumFractionDigits??0,e.maximumFractionDigits??e.minimumFractionDigits??0,e.grouping??groupingForLocale(localeOf(e)))}%`};const SYMBOLS={INR:"₹",USD:"$",EUR:"€",GBP:"£"},MINOR_DIGITS={JPY:0,KRW:0,VND:0,BHD:3,JOD:3,KWD:3,OMR:3,TND:3};export const formatMinor=(t,e)=>{if(!e?.currency)throw new TypeError('formatMinor needs options.currency, an ISO 4217 code such as "INR".');const n=toNumber(t);if(null===n)return emptyOf(e.empty);const r=e.currency.toUpperCase(),o=MINOR_DIGITS[r]??2,i=Math.round(Math.abs(n)),a=String(i).padStart(o+1,"0"),m=a.slice(0,a.length-o);let l=a.slice(a.length-o);e.dropZeroDecimals&&/^0*$/.test(l)&&(l="");const u=intlTextLocale({grouping:e.grouping});if(u)try{const t=Number(`${n<0&&0!==i?"-":""}${m}.${a.slice(a.length-o)||"0"}`);return styledNumber(numberFormat(u,{...!1===e.symbol?{}:{style:"currency",currency:r},...fractionDigits(l?o:0,o),...groupingOption(e.grouping)}),t)}catch(t){if(t instanceof RangeError)throw new RangeError(`formatMinor rejected currency "${r}" or locale "${u}": ${t.message}`,{cause:t});throw t}const c=e.grouping??("INR"===r?"indian":"international"),s=houseSeparators(),g=groupInteger(m,c,s.group)+(l?`${s.decimal}${l}`:""),p=n<0&&0!==i?"-":"";if(!1===e.symbol)return`${p}${g}`;const f=SYMBOLS[r];return f?`${p}${f}${g}`:`${p}${r} ${g}`};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{numberSeparators,styledNumber}from"./formatConfig.js";import{formatNumber as houseNumber,formatPercent as housePercent}from"./house.js";import{numberFormat}from"./intlCache.js";const hasIntlNumber=()=>"undefined"!=typeof Intl&&"function"==typeof Intl.NumberFormat,withDecimalMark=
|
|
1
|
+
"use strict";import{numberSeparators,styledNumber}from"./formatConfig.js";import{formatNumber as houseNumber,formatPercent as housePercent}from"./house.js";import{numberFormat}from"./intlCache.js";const hasIntlNumber=()=>"undefined"!=typeof Intl&&"function"==typeof Intl.NumberFormat,withDecimalMark=e=>{const r=numberSeparators();return null===r?e:e.replace(".",r.decimal)};export function formatNumber(e,r,t){if("number"!=typeof r&&void 0===t)return houseNumber(e,r);const o="number"==typeof r?r:void 0,n=e;if(null==n||Number.isNaN(n))return"";if(hasIntlNumber())try{const e={};return null!=o&&(e.minimumFractionDigits=o,e.maximumFractionDigits=o),styledNumber(numberFormat(t??"en-IN",e),n)}catch(e){if(e instanceof RangeError)throw new RangeError(`[@webority/mobile-core] formatNumber rejected locale "${t??"en-IN"}" or fraction digits ${o}: ${e.message}`,{cause:e});throw e}return withDecimalMark(null!=o?n.toFixed(o):String(n))}export function formatPercent(e,r,t,o){if("number"!=typeof r&&void 0===t&&void 0===o)return housePercent(e,r);const n="number"==typeof r?r:0,i=e;if(null==i||Number.isNaN(i))return"";const a=t??1?i:i/100;if(hasIntlNumber())try{return styledNumber(numberFormat(o??"en-IN",{style:"percent",minimumFractionDigits:n,maximumFractionDigits:n}),a)}catch(e){if(e instanceof RangeError)throw new RangeError(`[@webority/mobile-core] formatPercent rejected locale "${o??"en-IN"}" or fraction digits ${n}: ${e.message}`,{cause:e});throw e}return`${withDecimalMark((100*a).toFixed(n))}%`}export const formatCompactNumber=(e,r="en-IN")=>{if(null==e||Number.isNaN(e))return"";if(hasIntlNumber())try{return styledNumber(numberFormat(r,{notation:"compact",maximumFractionDigits:1}),e)}catch(e){if(e instanceof RangeError)throw new RangeError(`[@webority/mobile-core] formatCompactNumber rejected locale "${r}": ${e.message}`,{cause:e});throw e}const t=Math.abs(e),o=e<0?"-":"";return t>=1e7?`${o}${withDecimalMark((t/1e7).toFixed(1))}Cr`:t>=1e5?`${o}${withDecimalMark((t/1e5).toFixed(1))}L`:t>=1e3?`${o}${withDecimalMark((t/1e3).toFixed(1))}K`:withDecimalMark(`${e}`)};
|
|
@@ -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{}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.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};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webority/mobile-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.145.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",
|