@sveltekit-i18n/base 1.1.2 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  [![npm version](https://badge.fury.io/js/@sveltekit-i18n%2Fbase.svg)](https://badge.fury.io/js/@sveltekit-i18n%2Fbase) ![](https://github.com/sveltekit-i18n/base/workflows/Tests/badge.svg)
4
4
 
5
5
  # @sveltekit-i18n/base
6
- This repository contains the base functionality of [sveltekit-i18n](https://github.com/sveltekit-i18n/lib) and provides support for external message parsers.
6
+ This repository contains the base functionality of [sveltekit-i18n](https://github.com/sveltekit-i18n/lib) and provides support for external message [parsers](https://github.com/sveltekit-i18n/parsers).
7
7
 
8
8
 
9
9
  ## Key features
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- var y=Object.defineProperty,W=Object.defineProperties,D=Object.getOwnPropertyDescriptor,I=Object.getOwnPropertyDescriptors,H=Object.getOwnPropertyNames,L=Object.getOwnPropertySymbols;var x=Object.prototype.hasOwnProperty,K=Object.prototype.propertyIsEnumerable;var z=(a,t,e)=>t in a?y(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e,l=(a,t)=>{for(var e in t||(t={}))x.call(t,e)&&z(a,e,t[e]);if(L)for(var e of L(t))K.call(t,e)&&z(a,e,t[e]);return a},d=(a,t)=>W(a,I(t));var b=(a,t)=>{var e={};for(var s in a)x.call(a,s)&&t.indexOf(s)<0&&(e[s]=a[s]);if(a!=null&&L)for(var s of L(a))t.indexOf(s)<0&&K.call(a,s)&&(e[s]=a[s]);return e};var V=(a,t)=>{for(var e in t)y(a,e,{get:t[e],enumerable:!0})},M=(a,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of H(t))!x.call(a,r)&&r!==e&&y(a,r,{get:()=>t[r],enumerable:!(s=D(t,r))||s.enumerable});return a};var $=a=>M(y({},"__esModule",{value:!0}),a);var B={};V(B,{default:()=>R});module.exports=$(B);var n=require("svelte/store");var C=({parser:a,key:t,params:e,translations:s,locale:r,fallbackLocale:i})=>{if(!(t&&r))return console.warn("[i18n]: No translation key or locale provided. Skipping translation..."),"";let o=(s[r]||{})[t];return i&&o===void 0&&(o=(s[i]||{})[t]),a.parse(o,e,r,t)},h=(...a)=>a.length?a.filter(t=>!!t).map(t=>{let e=`${t}`.toLowerCase();try{if([e]=Intl.Collator.supportedLocalesOf(t),!e)throw new Error(`[i18n]: '${t}' is non-standard.`)}catch{console.warn(`[i18n]: Non-standard locale provided: '${t}'. Check your 'translations' and 'loaders' in i18n config...`)}return e}):[],T=(a,t)=>Object.keys(a||{}).reduce((e,s)=>{let r=a[s],i=t?`${t}.${s}`:`${s}`;return r&&typeof r=="object"?l(l({},e),T(r,i)):d(l({},e),{[i]:r})},{}),j=async a=>{try{return(await Promise.all(a.map(r=>{var i=r,{loader:e}=i,s=b(i,["loader"]);return new Promise(async o=>{let c;try{c=await e()}catch(P){console.error(`[i18n]: Failed to load translation. Verify your '${s.locale}' > '${s.key}' Loader.`),console.error(P)}o(d(l({loader:e},s),{data:c}))})}))).reduce((e,{key:s,data:r,locale:i})=>{if(!r)return e;let[o]=h(i);return d(l({},e),{[o]:T(d(l({},e[o]||{}),{[s]:r}))})},{})}catch(t){console.error(t)}return{}},k=a=>t=>{try{if(typeof t=="string")return t===a;if(typeof t=="object")return t.test(a)}catch{throw new Error("[i18n]: Invalid route config!")}return!1},N=(a,t)=>{let e=!0;try{e=Object.keys(a).filter(s=>a[s]!==void 0).every(s=>a[s]===t[s])}catch{}return e};var A=1e3*60*60*24,R=class{constructor(t){this.cachedAt=0;this.loadedKeys={};this.currentRoute=(0,n.writable)();this.config=(0,n.writable)();this.isLoading=(0,n.writable)(!1);this.promises=new Set;this.loading={subscribe:this.isLoading.subscribe,toPromise:(t,e)=>{let s=Array.from(this.promises).filter(r=>N({locale:h(t)[0],route:e},r)).map(({promise:r})=>r);return Promise.all(s)},get:()=>(0,n.get)(this.isLoading)};this.privateTranslations=(0,n.writable)({});this.translations={subscribe:this.privateTranslations.subscribe,get:()=>(0,n.get)(this.translations)};this.locales=d(l({},(0,n.derived)([this.config,this.privateTranslations],([t,e])=>{if(!t)return[];let{loaders:s=[]}=t,r=s.map(({locale:o})=>h(o)[0]),i=Object.keys(e).map(o=>h(o)[0]);return Array.from(new Set([...r,...i]))},[])),{get:()=>(0,n.get)(this.locales)});this.internalLocale=(0,n.writable)();this.loaderTrigger=(0,n.derived)([this.internalLocale,this.currentRoute],([t,e],s)=>{var r,i,o;t!==void 0&&e!==void 0&&(t!==((r=(0,n.get)(this.loaderTrigger))==null?void 0:r[0])||e!==((i=(0,n.get)(this.loaderTrigger))==null?void 0:i[1]))&&((o=(0,n.get)(this.config))!=null&&o.debug&&console.debug("[i18n]: Triggering translation load..."),s([t,e]))},[]);this.localeHelper=(0,n.writable)();this.locale={subscribe:this.localeHelper.subscribe,forceSet:this.localeHelper.set,set:this.internalLocale.set,update:this.internalLocale.update,get:()=>(0,n.get)(this.locale)};this.initialized=(0,n.derived)([this.locale,this.currentRoute,this.privateTranslations],([t,e,s],r)=>{(0,n.get)(this.initialized)||r(t!==void 0&&e!==void 0&&!!Object.keys(s).length)});this.translation=(0,n.derived)([this.privateTranslations,this.locale,this.isLoading],([t,e,s],r)=>{let i=t[e];i&&Object.keys(i).length&&!s&&r(i)},{});this.t=d(l({},(0,n.derived)([this.config,this.translation],([{parser:t,fallbackLocale:e}])=>(s,...r)=>C({parser:t,key:s,params:r,translations:this.translations.get(),locale:this.locale.get(),fallbackLocale:e}))),{get:(t,...e)=>(0,n.get)(this.t)(t,...e)});this.l=d(l({},(0,n.derived)([this.config,this.translations],([{parser:t,fallbackLocale:e},s])=>(r,i,...o)=>C({parser:t,key:i,params:o,translations:s,locale:r,fallbackLocale:e}))),{get:(t,e,...s)=>(0,n.get)(this.l)(t,e,...s)});this.getLocale=t=>{if(!t)return"";let s=this.locales.get().find(r=>r===h(t)[0])||"";return h(s)[0]||""};this.setLocale=t=>{var s;if(!t)return;let[e]=h(t);if(e!==(0,n.get)(this.internalLocale))return(s=(0,n.get)(this.config))!=null&&s.debug&&console.debug(`[i18n]: Setting '${e}' locale.`),this.internalLocale.set(e),this.loading.toPromise(t,(0,n.get)(this.currentRoute))};this.setRoute=t=>{var e;if(t!==(0,n.get)(this.currentRoute)){(e=(0,n.get)(this.config))!=null&&e.debug&&console.debug(`[i18n]: Setting '${t}' route.`),this.currentRoute.set(t);let s=(0,n.get)(this.internalLocale);return this.loading.toPromise(s,t)}};this.loadConfig=async t=>{await this.configLoader(t)};this.getTranslationProps=async(t=this.locale.get(),e=(0,n.get)(this.currentRoute))=>{let s=(0,n.get)(this.config);if(!s||!t)return[];let r=this.translations.get(),{loaders:i,fallbackLocale:o="",cache:c=A}=s||{},P=Number.isNaN(+c)?A:+c;this.cachedAt?Date.now()>P+this.cachedAt&&(s!=null&&s.debug&&console.debug("[i18n]: Refreshing cache."),this.loadedKeys={},this.cachedAt=0):(s!=null&&s.debug&&console.debug("[i18n]: Setting cache timestamp."),this.cachedAt=Date.now());let[v,S]=h(t,o),E=r[v],O=r[S],w=(i||[]).map(F=>{var u=F,{locale:g}=u,f=b(u,["locale"]);return d(l({},f),{locale:h(g)[0]})}).filter(({routes:g})=>!g||(g||[]).some(k(e))).filter(({key:g,locale:f})=>f===v&&(!E||!(this.loadedKeys[v]||[]).includes(g))||o&&f===S&&(!O||!(this.loadedKeys[S]||[]).includes(g)));if(w.length){this.isLoading.set(!0),s!=null&&s.debug&&console.debug("[i18n]: Fetching translations...");let g=await j(w);this.isLoading.set(!1);let f=Object.keys(g).reduce((u,p)=>d(l({},u),{[p]:Object.keys(g[p])}),{}),F=w.filter(({key:u,locale:p})=>(f[p]||[]).some(m=>`${m}`.startsWith(u))).reduce((u,{key:p,locale:m})=>d(l({},u),{[m]:[...u[m]||[],p]}),{});return[g,F]}return[]};this.addTranslations=(t,e)=>{var r;if(!t)return;(r=(0,n.get)(this.config))!=null&&r.debug&&console.debug("[i18n]: Adding translations...");let s=Object.keys(t||{});this.privateTranslations.update(i=>s.reduce((o,c)=>d(l({},o),{[c]:l(l({},o[c]||{}),T(t[c]))}),i)),s.forEach(i=>{let o=Object.keys(t[i]).map(c=>`${c}`.split(".")[0]);e&&(o=e[i]),this.loadedKeys[i]=Array.from(new Set([...this.loadedKeys[i]||[],...o||[]]))})};this.loader=async([t,e])=>{var r;(r=(0,n.get)(this.config))!=null&&r.debug&&console.debug("[i18n]: Adding loader promise.");let s=(async()=>{let i=await this.getTranslationProps(t,e);i.length&&this.addTranslations(...i)})();this.promises.add({locale:t,route:e,promise:s}),s.then(()=>{let i=this.getLocale(t);i&&this.locale.get()!==i&&this.locale.forceSet(i)})};this.loadTranslations=(t,e=(0,n.get)(this.currentRoute)||"")=>{if(!!t)return this.setRoute(e),this.setLocale(t),this.loading.toPromise(t,e)};t&&this.loadConfig(t),this.loaderTrigger.subscribe(this.loader),this.isLoading.subscribe(async e=>{var s;e&&this.promises.size&&(await this.loading.toPromise(),this.promises.clear(),(s=(0,n.get)(this.config))!=null&&s.debug&&console.debug("[i18n]: Loader promises have been purged."))})}async configLoader(t){if(!t)throw new Error("[i18n]: No config provided!");let c=t,{initLocale:e,fallbackLocale:s,translations:r,debug:i}=c,o=b(c,["initLocale","fallbackLocale","translations","debug"]);[e]=h(e),[s]=h(s),i&&console.debug("[i18n]: Setting config."),this.config.set(l({initLocale:e,fallbackLocale:s,translations:r,debug:i},o)),r&&this.addTranslations(r),await this.loadTranslations(e)}};0&&(module.exports={});
1
+ var x=Object.defineProperty,H=Object.defineProperties,M=Object.getOwnPropertyDescriptor,q=Object.getOwnPropertyDescriptors,B=Object.getOwnPropertyNames,v=Object.getOwnPropertySymbols;var R=Object.prototype.hasOwnProperty,N=Object.prototype.propertyIsEnumerable;var j=(s,e,t)=>e in s?x(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,l=(s,e)=>{for(var t in e||(e={}))R.call(e,t)&&j(s,t,e[t]);if(v)for(var t of v(e))N.call(e,t)&&j(s,t,e[t]);return s},d=(s,e)=>H(s,q(e));var m=(s,e)=>{var t={};for(var r in s)R.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&v)for(var r of v(s))e.indexOf(r)<0&&N.call(s,r)&&(t[r]=s[r]);return t};var G=(s,e)=>{for(var t in e)x(s,t,{get:e[t],enumerable:!0})},J=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of B(e))!R.call(s,a)&&a!==t&&x(s,a,{get:()=>e[a],enumerable:!(r=M(e,a))||r.enumerable});return s};var Q=s=>J(x({},"__esModule",{value:!0}),s);var U={};G(U,{default:()=>w});module.exports=Q(U);var n=require("svelte/store");var F=["error","warn","debug"],O=({logger:s=console,level:e=F[1],prefix:t="[i18n]: "})=>F.reduce((r,a,o)=>d(l({},r),{[a]:i=>F.indexOf(e)>=o&&s[a](`${t}${i}`)}),{}),c=O({}),V=s=>{c=s};var z=g=>{var u=g,{parser:s,key:e,params:t,translations:r,locale:a,fallbackLocale:o}=u,i=m(u,["parser","key","params","translations","locale","fallbackLocale"]);if(!(e&&a))return c.warn("No translation key or locale provided. Skipping translation..."),"";let p=(r[a]||{})[e];return o&&p===void 0&&(p=(r[o]||{})[e]),i.hasOwnProperty("fallbackValue")&&p===void 0?i.fallbackValue:s.parse(p,t,a,e)},f=(...s)=>s.length?s.filter(e=>!!e).map(e=>{let t=`${e}`.toLowerCase();try{let[r]=Intl.Collator.supportedLocalesOf(e);if(!r)throw new Error(`'${e}' is non-standard.`);t=r}catch{c.warn(`Non-standard locale provided: '${e}'. Check your 'translations' and 'loaders' in i18n config...`)}return t}):[],S=(s,e)=>Object.keys(s||{}).reduce((t,r)=>{let a=s[r],o=e?`${e}.${r}`:`${r}`;return a&&typeof a=="object"?l(l({},t),S(a,o)):d(l({},t),{[o]:a})},{}),$=async s=>{try{return(await Promise.all(s.map(a=>{var o=a,{loader:t}=o,r=m(o,["loader"]);return new Promise(async i=>{let g;try{g=await t()}catch(u){c.error(`Failed to load translation. Verify your '${r.locale}' > '${r.key}' Loader.`),c.error(u)}i(d(l({loader:t},r),{data:g}))})}))).reduce((t,{key:r,data:a,locale:o})=>{if(!a)return t;let[i]=f(o);return d(l({},t),{[i]:S(d(l({},t[i]||{}),{[r]:a}))})},{})}catch(e){c.error(e)}return{}},E=s=>e=>{try{if(typeof e=="string")return e===s;if(typeof e=="object")return e.test(s)}catch{c.error("Invalid route config!")}return!1},W=(s,e)=>{let t=!0;try{t=Object.keys(s).filter(r=>s[r]!==void 0).every(r=>s[r]===e[r])}catch{}return t};var D=1e3*60*60*24,w=class{constructor(e){this.cachedAt=0;this.loadedKeys={};this.currentRoute=(0,n.writable)();this.config=(0,n.writable)();this.isLoading=(0,n.writable)(!1);this.promises=new Set;this.loading={subscribe:this.isLoading.subscribe,toPromise:(e,t)=>{let r=Array.from(this.promises).filter(a=>W({locale:f(e)[0],route:t},a)).map(({promise:a})=>a);return Promise.all(r)},get:()=>(0,n.get)(this.isLoading)};this.privateTranslations=(0,n.writable)({});this.translations={subscribe:this.privateTranslations.subscribe,get:()=>(0,n.get)(this.translations)};this.locales=d(l({},(0,n.derived)([this.config,this.privateTranslations],([e,t])=>{if(!e)return[];let{loaders:r=[]}=e,a=r.map(({locale:i})=>i),o=Object.keys(t).map(i=>i);return Array.from(new Set([...f(...a),...f(...o)]))},[])),{get:()=>(0,n.get)(this.locales)});this.internalLocale=(0,n.writable)();this.loaderTrigger=(0,n.derived)([this.internalLocale,this.currentRoute],([e,t],r)=>{var a,o;e!==void 0&&t!==void 0&&!(e===((a=(0,n.get)(this.loaderTrigger))==null?void 0:a[0])&&t===((o=(0,n.get)(this.loaderTrigger))==null?void 0:o[1]))&&(c.debug("Triggering translation load..."),r([e,t]))},[]);this.localeHelper=(0,n.writable)();this.locale={subscribe:this.localeHelper.subscribe,forceSet:this.localeHelper.set,set:this.internalLocale.set,update:this.internalLocale.update,get:()=>(0,n.get)(this.locale)};this.initialized=(0,n.derived)([this.locale,this.currentRoute,this.privateTranslations],([e,t,r],a)=>{(0,n.get)(this.initialized)||a(e!==void 0&&t!==void 0&&!!Object.keys(r).length)});this.translation=(0,n.derived)([this.privateTranslations,this.locale,this.isLoading],([e,t,r],a)=>{let o=e[t];o&&Object.keys(o).length&&!r&&a(o)},{});this.t=d(l({},(0,n.derived)([this.config,this.translation],a=>{var[o]=a,i=o,{parser:e,fallbackLocale:t}=i,r=m(i,["parser","fallbackLocale"]);return(g,...u)=>z(l({parser:e,key:g,params:u,translations:this.translations.get(),locale:this.locale.get(),fallbackLocale:t},r.hasOwnProperty("fallbackValue")?{fallbackValue:r.fallbackValue}:{}))})),{get:(e,...t)=>(0,n.get)(this.t)(e,...t)});this.l=d(l({},(0,n.derived)([this.config,this.translations],o=>{var[i,...g]=o,u=i,{parser:e,fallbackLocale:t}=u,r=m(u,["parser","fallbackLocale"]),[a]=g;return(p,T,...k)=>z(l({parser:e,key:T,params:k,translations:a,locale:p,fallbackLocale:t},r.hasOwnProperty("fallbackValue")?{fallbackValue:r.fallbackValue}:{}))})),{get:(e,t,...r)=>(0,n.get)(this.l)(e,t,...r)});this.getLocale=e=>{let{fallbackLocale:t=""}=(0,n.get)(this.config)||{},r=e||t;if(!r)return"";let a=this.locales.get();return a.find(i=>f(r).includes(i))||a.find(i=>f(t).includes(i))||""};this.setLocale=e=>{if(!!e&&e!==(0,n.get)(this.internalLocale))return c.debug(`Setting '${e}' locale.`),this.internalLocale.set(e),this.loading.toPromise(e,(0,n.get)(this.currentRoute))};this.setRoute=e=>{if(e!==(0,n.get)(this.currentRoute)){c.debug(`Setting '${e}' route.`),this.currentRoute.set(e);let t=(0,n.get)(this.internalLocale);return this.loading.toPromise(t,e)}};this.loadConfig=async e=>{await this.configLoader(e)};this.getTranslationProps=async(e=this.locale.get(),t=(0,n.get)(this.currentRoute))=>{let r=(0,n.get)(this.config);if(!r||!e)return[];let a=this.translations.get(),{loaders:o,fallbackLocale:i="",cache:g=D}=r||{},u=Number.isNaN(+g)?D:+g;this.cachedAt?Date.now()>u+this.cachedAt&&(c.debug("Refreshing cache."),this.loadedKeys={},this.cachedAt=0):(c.debug("Setting cache timestamp."),this.cachedAt=Date.now());let[p,T]=f(e,i),k=a[p],I=a[T],C=(o||[]).map(K=>{var L=K,{locale:h}=L,b=m(L,["locale"]);return d(l({},b),{locale:f(h)[0]})}).filter(({routes:h})=>!h||(h||[]).some(E(t))).filter(({key:h,locale:b})=>b===p&&(!k||!(this.loadedKeys[p]||[]).includes(h))||i&&b===T&&(!I||!(this.loadedKeys[T]||[]).includes(h)));if(C.length){this.isLoading.set(!0),c.debug("Fetching translations...");let h=await $(C);this.isLoading.set(!1);let b=Object.keys(h).reduce((L,y)=>d(l({},L),{[y]:Object.keys(h[y])}),{}),K=C.filter(({key:L,locale:y})=>(b[y]||[]).some(P=>`${P}`.startsWith(L))).reduce((L,{key:y,locale:P})=>d(l({},L),{[P]:[...L[P]||[],y]}),{});return[h,K]}return[]};this.addTranslations=(e,t)=>{if(!e)return;c.debug("Adding translations...");let r=Object.keys(e||{});this.privateTranslations.update(a=>r.reduce((o,i)=>d(l({},o),{[i]:l(l({},o[i]||{}),S(e[i]))}),a)),r.forEach(a=>{let o=Object.keys(e[a]).map(i=>`${i}`.split(".")[0]);t&&(o=t[a]),this.loadedKeys[a]=Array.from(new Set([...this.loadedKeys[a]||[],...o||[]]))})};this.loader=async([e,t])=>{let r=this.getLocale(e);c.debug(`Adding loader promise for '${r}' locale and '${t}' route.`);let a=(async()=>{let o=await this.getTranslationProps(r,t);o.length&&this.addTranslations(...o)})();this.promises.add({locale:r,route:t,promise:a}),a.then(()=>{r&&this.locale.get()!==r&&this.locale.forceSet(r)})};this.loadTranslations=(e,t=(0,n.get)(this.currentRoute)||"")=>{let r=this.getLocale(e);if(!!r)return this.setRoute(t),this.setLocale(r),this.loading.toPromise(r,t)};this.loaderTrigger.subscribe(this.loader),this.isLoading.subscribe(async t=>{t&&this.promises.size&&(await this.loading.toPromise(),this.promises.clear(),c.debug("Loader promises have been purged."))}),e&&this.loadConfig(e)}async configLoader(e){if(!e)return c.error("No config provided!");let g=e,{initLocale:t,fallbackLocale:r,translations:a,log:o}=g,i=m(g,["initLocale","fallbackLocale","translations","log"]);o&&V(O(o)),[t]=f(t),[r]=f(r),c.debug("Setting config."),this.config.set(l({initLocale:t,fallbackLocale:r,translations:a},i)),a&&this.addTranslations(a),await this.loadTranslations(t)}};0&&(module.exports={});
package/dist/index.d.ts CHANGED
@@ -14,20 +14,38 @@ declare module DotNotation {
14
14
  };
15
15
  type T = <I = Input>(input: I, parentKey?: string) => Output<I>;
16
16
  }
17
+ declare module Logger {
18
+ type Level = 'error' | 'warn' | 'debug';
19
+ type Prefix = string;
20
+ type T = {
21
+ [key in Logger.Level]: (value: any) => void;
22
+ };
23
+ type FactoryProps = {
24
+ logger?: Logger.T;
25
+ level?: Logger.Level;
26
+ prefix?: Logger.Prefix;
27
+ };
28
+ }
17
29
  declare module Config {
18
30
  type Loader = Loader.LoaderModule;
19
31
  type Translations = Translations.T;
20
32
  type Locale = Translations.Locales[number];
21
33
  type InitLocale = Locale | undefined;
22
34
  type FallbackLocale = Locale | undefined;
35
+ type FallbackValue = any;
23
36
  type T<P extends Parser.Params = Parser.Params> = {
24
37
  loaders?: Loader[];
25
38
  translations?: Translations.T;
26
39
  initLocale?: InitLocale;
27
40
  fallbackLocale?: FallbackLocale;
41
+ fallbackValue?: FallbackValue;
28
42
  parser: Parser.T<P>;
29
43
  cache?: number;
30
- debug?: boolean;
44
+ log?: {
45
+ level?: Logger.Level;
46
+ logger?: Logger.T;
47
+ prefix?: Logger.Prefix;
48
+ };
31
49
  };
32
50
  }
33
51
  declare module Loader {
@@ -66,7 +84,8 @@ declare module Translations {
66
84
  params: P;
67
85
  translations: SerializedTranslations;
68
86
  locale: Locales[number];
69
- fallbackLocale?: string;
87
+ fallbackLocale?: Config.FallbackLocale;
88
+ fallbackValue?: Config.FallbackValue;
70
89
  }) => string;
71
90
  type Input<V = any> = {
72
91
  [K in any]: Input<V> | V;
@@ -111,4 +130,4 @@ declare class I18n<ParserParams extends Parser.Params = any> {
111
130
  loadTranslations: (locale: Config.Locale, route?: string) => Promise<void | void[]> | undefined;
112
131
  }
113
132
 
114
- export { Config, Loader, Parser, Translations, I18n as default };
133
+ export { Config, Loader, Logger, Parser, Translations, I18n as default };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- var D=Object.defineProperty,I=Object.defineProperties;var H=Object.getOwnPropertyDescriptors;var T=Object.getOwnPropertySymbols;var z=Object.prototype.hasOwnProperty,K=Object.prototype.propertyIsEnumerable;var F=(i,t,e)=>t in i?D(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,l=(i,t)=>{for(var e in t||(t={}))z.call(t,e)&&F(i,e,t[e]);if(T)for(var e of T(t))K.call(t,e)&&F(i,e,t[e]);return i},d=(i,t)=>I(i,H(t));var L=(i,t)=>{var e={};for(var s in i)z.call(i,s)&&t.indexOf(s)<0&&(e[s]=i[s]);if(i!=null&&T)for(var s of T(i))t.indexOf(s)<0&&K.call(i,s)&&(e[s]=i[s]);return e};import{derived as b,get as o,writable as m}from"svelte/store";var C=({parser:i,key:t,params:e,translations:s,locale:r,fallbackLocale:a})=>{if(!(t&&r))return console.warn("[i18n]: No translation key or locale provided. Skipping translation..."),"";let n=(s[r]||{})[t];return a&&n===void 0&&(n=(s[a]||{})[t]),i.parse(n,e,r,t)},h=(...i)=>i.length?i.filter(t=>!!t).map(t=>{let e=`${t}`.toLowerCase();try{if([e]=Intl.Collator.supportedLocalesOf(t),!e)throw new Error(`[i18n]: '${t}' is non-standard.`)}catch{console.warn(`[i18n]: Non-standard locale provided: '${t}'. Check your 'translations' and 'loaders' in i18n config...`)}return e}):[],P=(i,t)=>Object.keys(i||{}).reduce((e,s)=>{let r=i[s],a=t?`${t}.${s}`:`${s}`;return r&&typeof r=="object"?l(l({},e),P(r,a)):d(l({},e),{[a]:r})},{}),j=async i=>{try{return(await Promise.all(i.map(r=>{var a=r,{loader:e}=a,s=L(a,["loader"]);return new Promise(async n=>{let c;try{c=await e()}catch(v){console.error(`[i18n]: Failed to load translation. Verify your '${s.locale}' > '${s.key}' Loader.`),console.error(v)}n(d(l({loader:e},s),{data:c}))})}))).reduce((e,{key:s,data:r,locale:a})=>{if(!r)return e;let[n]=h(a);return d(l({},e),{[n]:P(d(l({},e[n]||{}),{[s]:r}))})},{})}catch(t){console.error(t)}return{}},k=i=>t=>{try{if(typeof t=="string")return t===i;if(typeof t=="object")return t.test(i)}catch{throw new Error("[i18n]: Invalid route config!")}return!1},N=(i,t)=>{let e=!0;try{e=Object.keys(i).filter(s=>i[s]!==void 0).every(s=>i[s]===t[s])}catch{}return e};var A=1e3*60*60*24,E=class{constructor(t){this.cachedAt=0;this.loadedKeys={};this.currentRoute=m();this.config=m();this.isLoading=m(!1);this.promises=new Set;this.loading={subscribe:this.isLoading.subscribe,toPromise:(t,e)=>{let s=Array.from(this.promises).filter(r=>N({locale:h(t)[0],route:e},r)).map(({promise:r})=>r);return Promise.all(s)},get:()=>o(this.isLoading)};this.privateTranslations=m({});this.translations={subscribe:this.privateTranslations.subscribe,get:()=>o(this.translations)};this.locales=d(l({},b([this.config,this.privateTranslations],([t,e])=>{if(!t)return[];let{loaders:s=[]}=t,r=s.map(({locale:n})=>h(n)[0]),a=Object.keys(e).map(n=>h(n)[0]);return Array.from(new Set([...r,...a]))},[])),{get:()=>o(this.locales)});this.internalLocale=m();this.loaderTrigger=b([this.internalLocale,this.currentRoute],([t,e],s)=>{var r,a,n;t!==void 0&&e!==void 0&&(t!==((r=o(this.loaderTrigger))==null?void 0:r[0])||e!==((a=o(this.loaderTrigger))==null?void 0:a[1]))&&((n=o(this.config))!=null&&n.debug&&console.debug("[i18n]: Triggering translation load..."),s([t,e]))},[]);this.localeHelper=m();this.locale={subscribe:this.localeHelper.subscribe,forceSet:this.localeHelper.set,set:this.internalLocale.set,update:this.internalLocale.update,get:()=>o(this.locale)};this.initialized=b([this.locale,this.currentRoute,this.privateTranslations],([t,e,s],r)=>{o(this.initialized)||r(t!==void 0&&e!==void 0&&!!Object.keys(s).length)});this.translation=b([this.privateTranslations,this.locale,this.isLoading],([t,e,s],r)=>{let a=t[e];a&&Object.keys(a).length&&!s&&r(a)},{});this.t=d(l({},b([this.config,this.translation],([{parser:t,fallbackLocale:e}])=>(s,...r)=>C({parser:t,key:s,params:r,translations:this.translations.get(),locale:this.locale.get(),fallbackLocale:e}))),{get:(t,...e)=>o(this.t)(t,...e)});this.l=d(l({},b([this.config,this.translations],([{parser:t,fallbackLocale:e},s])=>(r,a,...n)=>C({parser:t,key:a,params:n,translations:s,locale:r,fallbackLocale:e}))),{get:(t,e,...s)=>o(this.l)(t,e,...s)});this.getLocale=t=>{if(!t)return"";let s=this.locales.get().find(r=>r===h(t)[0])||"";return h(s)[0]||""};this.setLocale=t=>{var s;if(!t)return;let[e]=h(t);if(e!==o(this.internalLocale))return(s=o(this.config))!=null&&s.debug&&console.debug(`[i18n]: Setting '${e}' locale.`),this.internalLocale.set(e),this.loading.toPromise(t,o(this.currentRoute))};this.setRoute=t=>{var e;if(t!==o(this.currentRoute)){(e=o(this.config))!=null&&e.debug&&console.debug(`[i18n]: Setting '${t}' route.`),this.currentRoute.set(t);let s=o(this.internalLocale);return this.loading.toPromise(s,t)}};this.loadConfig=async t=>{await this.configLoader(t)};this.getTranslationProps=async(t=this.locale.get(),e=o(this.currentRoute))=>{let s=o(this.config);if(!s||!t)return[];let r=this.translations.get(),{loaders:a,fallbackLocale:n="",cache:c=A}=s||{},v=Number.isNaN(+c)?A:+c;this.cachedAt?Date.now()>v+this.cachedAt&&(s!=null&&s.debug&&console.debug("[i18n]: Refreshing cache."),this.loadedKeys={},this.cachedAt=0):(s!=null&&s.debug&&console.debug("[i18n]: Setting cache timestamp."),this.cachedAt=Date.now());let[S,w]=h(t,n),O=r[S],W=r[w],x=(a||[]).map(R=>{var u=R,{locale:g}=u,f=L(u,["locale"]);return d(l({},f),{locale:h(g)[0]})}).filter(({routes:g})=>!g||(g||[]).some(k(e))).filter(({key:g,locale:f})=>f===S&&(!O||!(this.loadedKeys[S]||[]).includes(g))||n&&f===w&&(!W||!(this.loadedKeys[w]||[]).includes(g)));if(x.length){this.isLoading.set(!0),s!=null&&s.debug&&console.debug("[i18n]: Fetching translations...");let g=await j(x);this.isLoading.set(!1);let f=Object.keys(g).reduce((u,p)=>d(l({},u),{[p]:Object.keys(g[p])}),{}),R=x.filter(({key:u,locale:p})=>(f[p]||[]).some(y=>`${y}`.startsWith(u))).reduce((u,{key:p,locale:y})=>d(l({},u),{[y]:[...u[y]||[],p]}),{});return[g,R]}return[]};this.addTranslations=(t,e)=>{var r;if(!t)return;(r=o(this.config))!=null&&r.debug&&console.debug("[i18n]: Adding translations...");let s=Object.keys(t||{});this.privateTranslations.update(a=>s.reduce((n,c)=>d(l({},n),{[c]:l(l({},n[c]||{}),P(t[c]))}),a)),s.forEach(a=>{let n=Object.keys(t[a]).map(c=>`${c}`.split(".")[0]);e&&(n=e[a]),this.loadedKeys[a]=Array.from(new Set([...this.loadedKeys[a]||[],...n||[]]))})};this.loader=async([t,e])=>{var r;(r=o(this.config))!=null&&r.debug&&console.debug("[i18n]: Adding loader promise.");let s=(async()=>{let a=await this.getTranslationProps(t,e);a.length&&this.addTranslations(...a)})();this.promises.add({locale:t,route:e,promise:s}),s.then(()=>{let a=this.getLocale(t);a&&this.locale.get()!==a&&this.locale.forceSet(a)})};this.loadTranslations=(t,e=o(this.currentRoute)||"")=>{if(!!t)return this.setRoute(e),this.setLocale(t),this.loading.toPromise(t,e)};t&&this.loadConfig(t),this.loaderTrigger.subscribe(this.loader),this.isLoading.subscribe(async e=>{var s;e&&this.promises.size&&(await this.loading.toPromise(),this.promises.clear(),(s=o(this.config))!=null&&s.debug&&console.debug("[i18n]: Loader promises have been purged."))})}async configLoader(t){if(!t)throw new Error("[i18n]: No config provided!");let c=t,{initLocale:e,fallbackLocale:s,translations:r,debug:a}=c,n=L(c,["initLocale","fallbackLocale","translations","debug"]);[e]=h(e),[s]=h(s),a&&console.debug("[i18n]: Setting config."),this.config.set(l({initLocale:e,fallbackLocale:s,translations:r,debug:a},n)),r&&this.addTranslations(r),await this.loadTranslations(e)}};export{E as default};
1
+ var q=Object.defineProperty,B=Object.defineProperties;var G=Object.getOwnPropertyDescriptors;var S=Object.getOwnPropertySymbols;var N=Object.prototype.hasOwnProperty,A=Object.prototype.propertyIsEnumerable;var j=(s,e,t)=>e in s?q(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,n=(s,e)=>{for(var t in e||(e={}))N.call(e,t)&&j(s,t,e[t]);if(S)for(var t of S(e))A.call(e,t)&&j(s,t,e[t]);return s},d=(s,e)=>B(s,G(e));var m=(s,e)=>{var t={};for(var r in s)N.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&S)for(var r of S(s))e.indexOf(r)<0&&A.call(s,r)&&(t[r]=s[r]);return t};import{derived as T,get as c,writable as P}from"svelte/store";var R=["error","warn","debug"],F=({logger:s=console,level:e=R[1],prefix:t="[i18n]: "})=>R.reduce((r,a,o)=>d(n({},r),{[a]:i=>R.indexOf(e)>=o&&s[a](`${t}${i}`)}),{}),l=F({}),E=s=>{l=s};var O=g=>{var u=g,{parser:s,key:e,params:t,translations:r,locale:a,fallbackLocale:o}=u,i=m(u,["parser","key","params","translations","locale","fallbackLocale"]);if(!(e&&a))return l.warn("No translation key or locale provided. Skipping translation..."),"";let p=(r[a]||{})[e];return o&&p===void 0&&(p=(r[o]||{})[e]),i.hasOwnProperty("fallbackValue")&&p===void 0?i.fallbackValue:s.parse(p,t,a,e)},f=(...s)=>s.length?s.filter(e=>!!e).map(e=>{let t=`${e}`.toLowerCase();try{let[r]=Intl.Collator.supportedLocalesOf(e);if(!r)throw new Error(`'${e}' is non-standard.`);t=r}catch{l.warn(`Non-standard locale provided: '${e}'. Check your 'translations' and 'loaders' in i18n config...`)}return t}):[],w=(s,e)=>Object.keys(s||{}).reduce((t,r)=>{let a=s[r],o=e?`${e}.${r}`:`${r}`;return a&&typeof a=="object"?n(n({},t),w(a,o)):d(n({},t),{[o]:a})},{}),W=async s=>{try{return(await Promise.all(s.map(a=>{var o=a,{loader:t}=o,r=m(o,["loader"]);return new Promise(async i=>{let g;try{g=await t()}catch(u){l.error(`Failed to load translation. Verify your '${r.locale}' > '${r.key}' Loader.`),l.error(u)}i(d(n({loader:t},r),{data:g}))})}))).reduce((t,{key:r,data:a,locale:o})=>{if(!a)return t;let[i]=f(o);return d(n({},t),{[i]:w(d(n({},t[i]||{}),{[r]:a}))})},{})}catch(e){l.error(e)}return{}},D=s=>e=>{try{if(typeof e=="string")return e===s;if(typeof e=="object")return e.test(s)}catch{l.error("Invalid route config!")}return!1},I=(s,e)=>{let t=!0;try{t=Object.keys(s).filter(r=>s[r]!==void 0).every(r=>s[r]===e[r])}catch{}return t};var H=1e3*60*60*24,z=class{constructor(e){this.cachedAt=0;this.loadedKeys={};this.currentRoute=P();this.config=P();this.isLoading=P(!1);this.promises=new Set;this.loading={subscribe:this.isLoading.subscribe,toPromise:(e,t)=>{let r=Array.from(this.promises).filter(a=>I({locale:f(e)[0],route:t},a)).map(({promise:a})=>a);return Promise.all(r)},get:()=>c(this.isLoading)};this.privateTranslations=P({});this.translations={subscribe:this.privateTranslations.subscribe,get:()=>c(this.translations)};this.locales=d(n({},T([this.config,this.privateTranslations],([e,t])=>{if(!e)return[];let{loaders:r=[]}=e,a=r.map(({locale:i})=>i),o=Object.keys(t).map(i=>i);return Array.from(new Set([...f(...a),...f(...o)]))},[])),{get:()=>c(this.locales)});this.internalLocale=P();this.loaderTrigger=T([this.internalLocale,this.currentRoute],([e,t],r)=>{var a,o;e!==void 0&&t!==void 0&&!(e===((a=c(this.loaderTrigger))==null?void 0:a[0])&&t===((o=c(this.loaderTrigger))==null?void 0:o[1]))&&(l.debug("Triggering translation load..."),r([e,t]))},[]);this.localeHelper=P();this.locale={subscribe:this.localeHelper.subscribe,forceSet:this.localeHelper.set,set:this.internalLocale.set,update:this.internalLocale.update,get:()=>c(this.locale)};this.initialized=T([this.locale,this.currentRoute,this.privateTranslations],([e,t,r],a)=>{c(this.initialized)||a(e!==void 0&&t!==void 0&&!!Object.keys(r).length)});this.translation=T([this.privateTranslations,this.locale,this.isLoading],([e,t,r],a)=>{let o=e[t];o&&Object.keys(o).length&&!r&&a(o)},{});this.t=d(n({},T([this.config,this.translation],a=>{var[o]=a,i=o,{parser:e,fallbackLocale:t}=i,r=m(i,["parser","fallbackLocale"]);return(g,...u)=>O(n({parser:e,key:g,params:u,translations:this.translations.get(),locale:this.locale.get(),fallbackLocale:t},r.hasOwnProperty("fallbackValue")?{fallbackValue:r.fallbackValue}:{}))})),{get:(e,...t)=>c(this.t)(e,...t)});this.l=d(n({},T([this.config,this.translations],o=>{var[i,...g]=o,u=i,{parser:e,fallbackLocale:t}=u,r=m(u,["parser","fallbackLocale"]),[a]=g;return(p,v,...k)=>O(n({parser:e,key:v,params:k,translations:a,locale:p,fallbackLocale:t},r.hasOwnProperty("fallbackValue")?{fallbackValue:r.fallbackValue}:{}))})),{get:(e,t,...r)=>c(this.l)(e,t,...r)});this.getLocale=e=>{let{fallbackLocale:t=""}=c(this.config)||{},r=e||t;if(!r)return"";let a=this.locales.get();return a.find(i=>f(r).includes(i))||a.find(i=>f(t).includes(i))||""};this.setLocale=e=>{if(!!e&&e!==c(this.internalLocale))return l.debug(`Setting '${e}' locale.`),this.internalLocale.set(e),this.loading.toPromise(e,c(this.currentRoute))};this.setRoute=e=>{if(e!==c(this.currentRoute)){l.debug(`Setting '${e}' route.`),this.currentRoute.set(e);let t=c(this.internalLocale);return this.loading.toPromise(t,e)}};this.loadConfig=async e=>{await this.configLoader(e)};this.getTranslationProps=async(e=this.locale.get(),t=c(this.currentRoute))=>{let r=c(this.config);if(!r||!e)return[];let a=this.translations.get(),{loaders:o,fallbackLocale:i="",cache:g=H}=r||{},u=Number.isNaN(+g)?H:+g;this.cachedAt?Date.now()>u+this.cachedAt&&(l.debug("Refreshing cache."),this.loadedKeys={},this.cachedAt=0):(l.debug("Setting cache timestamp."),this.cachedAt=Date.now());let[p,v]=f(e,i),k=a[p],M=a[v],C=(o||[]).map(K=>{var L=K,{locale:h}=L,b=m(L,["locale"]);return d(n({},b),{locale:f(h)[0]})}).filter(({routes:h})=>!h||(h||[]).some(D(t))).filter(({key:h,locale:b})=>b===p&&(!k||!(this.loadedKeys[p]||[]).includes(h))||i&&b===v&&(!M||!(this.loadedKeys[v]||[]).includes(h)));if(C.length){this.isLoading.set(!0),l.debug("Fetching translations...");let h=await W(C);this.isLoading.set(!1);let b=Object.keys(h).reduce((L,y)=>d(n({},L),{[y]:Object.keys(h[y])}),{}),K=C.filter(({key:L,locale:y})=>(b[y]||[]).some(x=>`${x}`.startsWith(L))).reduce((L,{key:y,locale:x})=>d(n({},L),{[x]:[...L[x]||[],y]}),{});return[h,K]}return[]};this.addTranslations=(e,t)=>{if(!e)return;l.debug("Adding translations...");let r=Object.keys(e||{});this.privateTranslations.update(a=>r.reduce((o,i)=>d(n({},o),{[i]:n(n({},o[i]||{}),w(e[i]))}),a)),r.forEach(a=>{let o=Object.keys(e[a]).map(i=>`${i}`.split(".")[0]);t&&(o=t[a]),this.loadedKeys[a]=Array.from(new Set([...this.loadedKeys[a]||[],...o||[]]))})};this.loader=async([e,t])=>{let r=this.getLocale(e);l.debug(`Adding loader promise for '${r}' locale and '${t}' route.`);let a=(async()=>{let o=await this.getTranslationProps(r,t);o.length&&this.addTranslations(...o)})();this.promises.add({locale:r,route:t,promise:a}),a.then(()=>{r&&this.locale.get()!==r&&this.locale.forceSet(r)})};this.loadTranslations=(e,t=c(this.currentRoute)||"")=>{let r=this.getLocale(e);if(!!r)return this.setRoute(t),this.setLocale(r),this.loading.toPromise(r,t)};this.loaderTrigger.subscribe(this.loader),this.isLoading.subscribe(async t=>{t&&this.promises.size&&(await this.loading.toPromise(),this.promises.clear(),l.debug("Loader promises have been purged."))}),e&&this.loadConfig(e)}async configLoader(e){if(!e)return l.error("No config provided!");let g=e,{initLocale:t,fallbackLocale:r,translations:a,log:o}=g,i=m(g,["initLocale","fallbackLocale","translations","log"]);o&&E(F(o)),[t]=f(t),[r]=f(r),l.debug("Setting config."),this.config.set(n({initLocale:t,fallbackLocale:r,translations:a},i)),a&&this.addTranslations(a),await this.loadTranslations(t)}};export{z as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sveltekit-i18n/base",
3
- "version": "1.1.2",
3
+ "version": "1.2.1",
4
4
  "description": "Base functionality of sveltekit-i18n library with a support for external message parsers.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -57,7 +57,7 @@
57
57
  "@typescript-eslint/eslint-plugin": "^5.7.0",
58
58
  "@typescript-eslint/parser": "^5.7.0",
59
59
  "eslint": "^8.4.1",
60
- "eslint-config-airbnb-typescript": "^16.1.0",
60
+ "eslint-config-airbnb-typescript": "^17.0.0",
61
61
  "eslint-plugin-import": "^2.25.3",
62
62
  "jest": "^27.4.5",
63
63
  "pre-commit": "^1.2.2",