@sveltekit-i18n/base 1.0.0-rc.5 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,9 +3,8 @@
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 a 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.
7
7
 
8
- __IMPORTANT: THIS PACKAGE IS STILL IN DEVELOPMENT - API MAY VARY UNTIL 1.0.0__
9
8
 
10
9
  ## Key features
11
10
 
@@ -23,11 +22,13 @@ __IMPORTANT: THIS PACKAGE IS STILL IN DEVELOPMENT - API MAY VARY UNTIL 1.0.0__
23
22
  Setup `translations.js` in your lib folder...
24
23
  ```javascript
25
24
  import i18n from '@sveltekit-i18n/base';
26
- import parser from '@sveltekit-i18n/parser-default'; // use your preferred parser (or create your own)
25
+ // use your preferred parser (or create your own)
26
+ import parser from '@sveltekit-i18n/parser-default';
27
+ // import parser from '@sveltekit-i18n/parser-icu';
27
28
 
28
- /** @namespace {import('@sveltekit-i18n/parser-default').Config} */
29
+ /** @type {import('@sveltekit-i18n/parser-default').Config} */
29
30
  const config = ({
30
- parser: parser({}),
31
+ parser: parser({/* Parser options */}),
31
32
  loaders: [
32
33
  {
33
34
  locale: 'en',
@@ -94,7 +95,7 @@ export const { t, locale, locales, loading, loadTranslations } = new i18n(config
94
95
 
95
96
  const initLocale = locale.get() || defaultLocale; // set default if no locale already set
96
97
 
97
- await loadTranslations(initLocale, pathname);
98
+ await loadTranslations(initLocale, pathname); // keep this just before the `return`
98
99
 
99
100
  return {};
100
101
  }
@@ -111,7 +112,6 @@ export const { t, locale, locales, loading, loadTranslations } = new i18n(config
111
112
  </script>
112
113
 
113
114
  <div>
114
- <!-- you can use `placeholders` and `modifiers` in your definitions (see docs) -->
115
115
  <h2>{$t('common.page', { pageName })}</h2>
116
116
  <p>{$t('home.content')}</p>
117
117
  </div>
@@ -119,6 +119,7 @@ export const { t, locale, locales, loading, loadTranslations } = new i18n(config
119
119
 
120
120
 
121
121
  ## More info
122
+ [Parsers](https://github.com/sveltekit-i18n/parsers)\
122
123
  [Docs](https://github.com/sveltekit-i18n/base/tree/master/docs/README.md)\
123
124
  [Examples](https://github.com/sveltekit-i18n/lib/tree/master/examples#parsers)\
124
125
  [Changelog](https://github.com/sveltekit-i18n/base/releases)
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- var P=Object.defineProperty,k=Object.defineProperties,E=Object.getOwnPropertyDescriptor,O=Object.getOwnPropertyDescriptors,z=Object.getOwnPropertyNames,m=Object.getOwnPropertySymbols;var w=Object.prototype.hasOwnProperty,S=Object.prototype.propertyIsEnumerable;var R=(r,t,e)=>t in r?P(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e,l=(r,t)=>{for(var e in t||(t={}))w.call(t,e)&&R(r,e,t[e]);if(m)for(var e of m(t))S.call(t,e)&&R(r,e,t[e]);return r},c=(r,t)=>k(r,O(t)),W=r=>P(r,"__esModule",{value:!0});var T=(r,t)=>{var e={};for(var a in r)w.call(r,a)&&t.indexOf(a)<0&&(e[a]=r[a]);if(r!=null&&m)for(var a of m(r))t.indexOf(a)<0&&S.call(r,a)&&(e[a]=r[a]);return e};var I=(r,t)=>{for(var e in t)P(r,e,{get:t[e],enumerable:!0})},N=(r,t,e,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of z(t))!w.call(r,s)&&(e||s!=="default")&&P(r,s,{get:()=>t[s],enumerable:!(a=E(t,s))||a.enumerable});return r};var D=(r=>(t,e)=>r&&r.get(t)||(e=N(W({}),t,1),r&&r.set(t,e),e))(typeof WeakMap!="undefined"?new WeakMap:0);var M={};I(M,{default:()=>C});var n=require("svelte/store");var f=r=>{if(!r)return[];let t=r;return Array.isArray(t)||(t=[t]),t.map(e=>{let a=`${e}`.toLowerCase();try{[a]=Intl.Collator.supportedLocalesOf(e)}catch{console.warn("Unstandard locale provided! Check your `translations` and `loaders` in config...")}return a})},b=(r,t)=>Object.keys(r||{}).reduce((e,a)=>{let s=r[a],o=t?`${t}.${a}`:`${a}`;return s&&typeof s=="object"?l(l({},e),b(s,o)):c(l({},e),{[o]:s})},{}),F=async r=>{try{return(await Promise.all(r.map(s=>{var o=s,{loader:e}=o,a=T(o,["loader"]);return new Promise(async i=>{let h;try{h=await e()}catch(L){console.error(`Failed to load translation. Verify your '${a.locale}' > '${a.key}' Loader.`),console.error(L)}i(c(l({loader:e},a),{data:h}))})}))).reduce((e,{key:a,data:s,locale:o})=>{if(!s)return e;let i=f(o)[0];return c(l({},e),{[i]:b(c(l({},e[i]||{}),{[a]:s}))})},{})}catch(t){console.error(t)}return{}},$=r=>t=>{try{if(typeof t=="string")return t===r;if(typeof t=="object")return t.test(r)}catch{throw new Error("Invalid route config!")}return!1};var C=class{constructor(t){this.loadedKeys={};this.currentRoute=(0,n.writable)();this.config=(0,n.writable)();this.isLoading=(0,n.writable)(!1);this.promises=[];this.loading={subscribe:this.isLoading.subscribe,toPromise:()=>Promise.all(this.promises),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=c(l({},(0,n.derived)([this.config,this.privateTranslations],([t,e])=>{if(!t)return[];let{loaders:a=[]}=t,s=a.map(({locale:i})=>f(i)[0]),o=Object.keys(e).map(i=>f(i)[0]);return[...new Set([...s,...o])]},[])),{get:()=>(0,n.get)(this.locales)});this.internalLocale=(0,n.writable)();this.locale=c(l({set:this.internalLocale.set,update:this.internalLocale.update},(0,n.derived)(this.internalLocale,(t,e)=>{let a=this.getLocale(t);a&&a!==this.locale.get()&&e(a)})),{get:()=>(0,n.get)(this.locale)});this.loaderTrigger=(0,n.derived)([this.internalLocale,this.currentRoute],([t,e],a)=>{t!==void 0&&e!==void 0&&a([t,e])},[]);this.initialized=(0,n.derived)([this.locale,this.currentRoute,this.privateTranslations],([t,e,a],s)=>{(0,n.get)(this.initialized)||s(t!==void 0&&e!==void 0&&!!Object.keys(a).length)});this.translation=(0,n.derived)([this.privateTranslations,this.locale,this.isLoading],([t,e,a],s)=>{let o=t[e];o&&Object.keys(o).length&&!a&&s(o)},{});this.translate=({parser:t,key:e,params:a,translations:s,locale:o,fallbackLocale:i})=>{if(!(e&&o))return console.warn("No translation key or locale provided. Skipping translation..."),"";let h=(s[o]||{})[e];return i&&h===void 0&&(h=(s[i]||{})[e]),t.parse(h,a,o,e)};this.t=c(l({},(0,n.derived)([this.config,this.translation],([{parser:t,fallbackLocale:e}])=>(a,...s)=>this.translate({parser:t,key:a,params:s,translations:this.translations.get(),locale:this.locale.get(),fallbackLocale:e}))),{get:(t,...e)=>(0,n.get)(this.t)(t,...e)});this.l=c(l({},(0,n.derived)([this.config,this.translations],([{parser:t,fallbackLocale:e},a])=>(s,o,...i)=>this.translate({parser:t,key:o,params:i,translations:a,locale:s,fallbackLocale:e}))),{get:(t,e,...a)=>(0,n.get)(this.l)(t,e,...a)});this.getLocale=t=>{if(!t)return"";let a=this.locales.get().find(s=>`${f(s)}`==`${f(t)}`)||"";return`${f(a)}`};this.setLocale=async t=>{!t||(this.internalLocale.set(`${f(t)}`),await this.loading.toPromise())};this.setRoute=async t=>{t!==(0,n.get)(this.currentRoute)&&this.currentRoute.set(t),await this.loading.toPromise()};this.loadConfig=async t=>{await this.configLoader(t)};this.addTranslations=(t,e)=>{if(!t)return;let a=Object.keys(t||{});this.privateTranslations.update(s=>a.reduce((o,i)=>c(l({},o),{[i]:l(l({},o[i]||{}),b(t[i]))}),s)),a.forEach(s=>{let o=Object.keys(t[s]).map(i=>`${i}`.split(".")[0]);e&&(o=e[s]),this.loadedKeys[s]=Array.from(new Set([...this.loadedKeys[s]||[],...o||[]]))})};this.getTranslationProps=async(t=this.locale.get(),e=(0,n.get)(this.currentRoute))=>{let a=(0,n.get)(this.config);if(!a||!t)return[];let s=this.translations.get(),{loaders:o,fallbackLocale:i=""}=a||{},h=`${t}`.toLowerCase(),L=i&&`${i}`.toLowerCase(),K=s[h],j=s[L],v=(o||[]).map(x=>{var u=x,{locale:d}=u,g=T(u,["locale"]);return c(l({},g),{locale:`${d}`.toLowerCase()})}).filter(({routes:d})=>!d||(d||[]).some($(e))).filter(({key:d,locale:g})=>g===h&&(!K||!(this.loadedKeys[h]||[]).includes(d))||i&&g===L&&(!j||!(this.loadedKeys[L]||[]).includes(d)));if(v.length){this.isLoading.set(!0);let d=await F(v);this.isLoading.set(!1);let g=Object.keys(d).reduce((u,p)=>c(l({},u),{[p]:Object.keys(d[p])}),{}),x=v.filter(({key:u,locale:p})=>(g[p]||[]).some(y=>`${y}`.startsWith(u))).reduce((u,{key:p,locale:y})=>c(l({},u),{[y]:[...u[y]||[],p]}),{});return[d,x]}return[]};this.translationLoader=async t=>{this.promises.push(new Promise(async e=>{let a=await this.getTranslationProps(t);a.length&&this.addTranslations(...a),e()})),await this.loading.toPromise()};this.loadTranslations=async(t,e=(0,n.get)(this.currentRoute)||"")=>{!t||(this.setRoute(e),this.setLocale(t),await this.loading.toPromise())};t&&this.loadConfig(t),this.loaderTrigger.subscribe(()=>this.translationLoader())}async configLoader(t){if(!t)throw new Error("No config provided!");let i=t,{initLocale:e,fallbackLocale:a,translations:s}=i,o=T(i,["initLocale","fallbackLocale","translations"]);e=f(e)[0],a=f(a)[0],this.config.set(l({initLocale:e,fallbackLocale:a,translations:s},o)),s&&this.addTranslations(s),await this.loadTranslations(e)}};module.exports=D(M);0&&(module.exports={});
1
+ var T=Object.defineProperty,O=Object.defineProperties,A=Object.getOwnPropertyDescriptor,W=Object.getOwnPropertyDescriptors,D=Object.getOwnPropertyNames,y=Object.getOwnPropertySymbols;var x=Object.prototype.hasOwnProperty,K=Object.prototype.propertyIsEnumerable;var F=(r,t,e)=>t in r?T(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e,l=(r,t)=>{for(var e in t||(t={}))x.call(t,e)&&F(r,e,t[e]);if(y)for(var e of y(t))K.call(t,e)&&F(r,e,t[e]);return r},c=(r,t)=>O(r,W(t)),I=r=>T(r,"__esModule",{value:!0});var L=(r,t)=>{var e={};for(var s in r)x.call(r,s)&&t.indexOf(s)<0&&(e[s]=r[s]);if(r!=null&&y)for(var s of y(r))t.indexOf(s)<0&&K.call(r,s)&&(e[s]=r[s]);return e};var $=(r,t)=>{for(var e in t)T(r,e,{get:t[e],enumerable:!0})},V=(r,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of D(t))!x.call(r,a)&&(e||a!=="default")&&T(r,a,{get:()=>t[a],enumerable:!(s=A(t,a))||s.enumerable});return r};var M=(r=>(t,e)=>r&&r.get(t)||(e=V(I({}),t,1),r&&r.set(t,e),e))(typeof WeakMap!="undefined"?new WeakMap:0);var B={};$(B,{default:()=>R});var o=require("svelte/store");var h=r=>{if(!r||!r.length)return[];let t=r;return Array.isArray(t)||(t=[t]),t.filter(e=>!!e).map(e=>{let s=`${e}`.toLowerCase();try{[s]=Intl.Collator.supportedLocalesOf(e)}catch{console.warn(`Non-standard locale provided: '${r}' => '${t}'. Check your 'translations' and 'loaders' in i18n config...`)}return s})},P=(r,t)=>Object.keys(r||{}).reduce((e,s)=>{let a=r[s],i=t?`${t}.${s}`:`${s}`;return a&&typeof a=="object"?l(l({},e),P(a,i)):c(l({},e),{[i]:a})},{}),N=async r=>{try{return(await Promise.all(r.map(a=>{var i=a,{loader:e}=i,s=L(i,["loader"]);return new Promise(async n=>{let f;try{f=await e()}catch(b){console.error(`Failed to load translation. Verify your '${s.locale}' > '${s.key}' Loader.`),console.error(b)}n(c(l({loader:e},s),{data:f}))})}))).reduce((e,{key:s,data:a,locale:i})=>{if(!a)return e;let n=h(i)[0];return c(l({},e),{[n]:P(c(l({},e[n]||{}),{[s]:a}))})},{})}catch(t){console.error(t)}return{}},j=r=>t=>{try{if(typeof t=="string")return t===r;if(typeof t=="object")return t.test(r)}catch{throw new Error("Invalid route config!")}return!1};var z=1e3*60*60*24,R=class{constructor(t){this.cachedAt=0;this.loadedKeys={};this.currentRoute=(0,o.writable)();this.config=(0,o.writable)();this.isLoading=(0,o.writable)(!1);this.promises=[];this.loading={subscribe:this.isLoading.subscribe,toPromise:t=>t?this.promises[t]:Promise.all(this.promises),get:()=>(0,o.get)(this.isLoading)};this.privateTranslations=(0,o.writable)({});this.translations={subscribe:this.privateTranslations.subscribe,get:()=>(0,o.get)(this.translations)};this.locales=c(l({},(0,o.derived)([this.config,this.privateTranslations],([t,e])=>{if(!t)return[];let{loaders:s=[]}=t,a=s.map(({locale:n})=>h(n)[0]),i=Object.keys(e).map(n=>h(n)[0]);return[...new Set([...a,...i])]},[])),{get:()=>(0,o.get)(this.locales)});this.internalLocale=(0,o.writable)();this.locale=c(l({set:this.internalLocale.set,update:this.internalLocale.update},(0,o.derived)(this.internalLocale,(t,e)=>{let s=this.getLocale(t);s&&s!==this.locale.get()&&e(s)})),{get:()=>(0,o.get)(this.locale)});this.loaderTrigger=(0,o.derived)([this.internalLocale,this.currentRoute],([t,e],s)=>{t!==void 0&&e!==void 0&&s([t,e])},[]);this.initialized=(0,o.derived)([this.locale,this.currentRoute,this.privateTranslations],([t,e,s],a)=>{(0,o.get)(this.initialized)||a(t!==void 0&&e!==void 0&&!!Object.keys(s).length)});this.translation=(0,o.derived)([this.privateTranslations,this.locale,this.isLoading],([t,e,s],a)=>{let i=t[e];i&&Object.keys(i).length&&!s&&a(i)},{});this.translate=({parser:t,key:e,params:s,translations:a,locale:i,fallbackLocale:n})=>{if(!(e&&i))return console.warn("No translation key or locale provided. Skipping translation..."),"";let f=(a[i]||{})[e];return n&&f===void 0&&(f=(a[n]||{})[e]),t.parse(f,s,i,e)};this.t=c(l({},(0,o.derived)([this.config,this.translation],([{parser:t,fallbackLocale:e}])=>(s,...a)=>this.translate({parser:t,key:s,params:a,translations:this.translations.get(),locale:this.locale.get(),fallbackLocale:e}))),{get:(t,...e)=>(0,o.get)(this.t)(t,...e)});this.l=c(l({},(0,o.derived)([this.config,this.translations],([{parser:t,fallbackLocale:e},s])=>(a,i,...n)=>this.translate({parser:t,key:i,params:n,translations:s,locale:a,fallbackLocale:e}))),{get:(t,e,...s)=>(0,o.get)(this.l)(t,e,...s)});this.getLocale=t=>{if(!t)return"";let s=this.locales.get().find(a=>a===h(t)[0])||"";return h(s)[0]||""};this.setLocale=async t=>{if(!t)return;let e=this.promises.length;this.internalLocale.set(h(t)[0]),await this.loading.toPromise(e)};this.setRoute=async t=>{let e=this.promises.length;t!==(0,o.get)(this.currentRoute)&&this.currentRoute.set(t),await this.loading.toPromise(e)};this.loadConfig=async t=>{await this.configLoader(t)};this.getTranslationProps=async(t=this.locale.get(),e=(0,o.get)(this.currentRoute))=>{let s=(0,o.get)(this.config);if(!s||!t)return[];let a=this.translations.get(),{loaders:i,fallbackLocale:n="",cache:f=z}=s||{},b=Number.isNaN(+f)?z:+f;this.cachedAt?Date.now()>b+this.cachedAt&&(this.loadedKeys={},this.cachedAt=0):this.cachedAt=Date.now();let[v,w]=h([t,n]),k=a[v],E=a[w],C=(i||[]).map(S=>{var g=S,{locale:d}=g,u=L(g,["locale"]);return c(l({},u),{locale:h(d)[0]})}).filter(({routes:d})=>!d||(d||[]).some(j(e))).filter(({key:d,locale:u})=>u===v&&(!k||!(this.loadedKeys[v]||[]).includes(d))||n&&u===w&&(!E||!(this.loadedKeys[w]||[]).includes(d)));if(C.length){this.isLoading.set(!0);let d=await N(C);this.isLoading.set(!1);let u=Object.keys(d).reduce((g,p)=>c(l({},g),{[p]:Object.keys(d[p])}),{}),S=C.filter(({key:g,locale:p})=>(u[p]||[]).some(m=>`${m}`.startsWith(g))).reduce((g,{key:p,locale:m})=>c(l({},g),{[m]:[...g[m]||[],p]}),{});return[d,S]}return[]};this.addTranslations=(t,e)=>{if(!t)return;let s=Object.keys(t||{});this.privateTranslations.update(a=>s.reduce((i,n)=>c(l({},i),{[n]:l(l({},i[n]||{}),P(t[n]))}),a)),s.forEach(a=>{let i=Object.keys(t[a]).map(n=>`${n}`.split(".")[0]);e&&(i=e[a]),this.loadedKeys[a]=Array.from(new Set([...this.loadedKeys[a]||[],...i||[]]))})};this.translationLoader=async t=>{let e=this.promises.length;this.promises.push(new Promise(async s=>{let a=await this.getTranslationProps(t);a.length&&this.addTranslations(...a),this.setLocale(t),s()})),await this.loading.toPromise(e)};this.loadTranslations=async(t,e=(0,o.get)(this.currentRoute)||"")=>{if(!t)return;let s=this.promises.length;this.setRoute(e),this.setLocale(t),await this.loading.toPromise(s)};t&&this.loadConfig(t),this.loaderTrigger.subscribe(([e])=>this.translationLoader(e)),this.isLoading.subscribe(async e=>{e&&(await this.loading.toPromise(),this.promises=[])})}async configLoader(t){if(!t)throw new Error("No config provided!");let n=t,{initLocale:e,fallbackLocale:s,translations:a}=n,i=L(n,["initLocale","fallbackLocale","translations"]);e=h(e)[0],s=h(s)[0],this.config.set(l({initLocale:e,fallbackLocale:s,translations:a},i)),a&&this.addTranslations(a),await this.loadTranslations(e)}};module.exports=M(B);0&&(module.exports={});
package/dist/index.d.ts CHANGED
@@ -4,7 +4,7 @@ declare type ExtendedStore<T, Get = () => T, Store = Readable<T>> = Store & {
4
4
  get: Get;
5
5
  };
6
6
  declare type LoadingStore = Readable<boolean> & {
7
- toPromise: () => Promise<void[]>;
7
+ toPromise: (id?: number) => Promise<void[] | void>;
8
8
  get: () => boolean;
9
9
  };
10
10
  declare module DotNotation {
@@ -26,6 +26,7 @@ declare module Config {
26
26
  initLocale?: InitLocale;
27
27
  fallbackLocale?: FallbackLocale;
28
28
  parser: Parser.T<P>;
29
+ cache?: number;
29
30
  };
30
31
  }
31
32
  declare module Loader {
@@ -77,6 +78,7 @@ declare module Translations {
77
78
 
78
79
  declare class I18n<ParserParams extends Parser.Params = any> {
79
80
  constructor(config?: Config.T<ParserParams>);
81
+ private cachedAt;
80
82
  private loadedKeys;
81
83
  private currentRoute;
82
84
  private config;
@@ -99,9 +101,9 @@ declare class I18n<ParserParams extends Parser.Params = any> {
99
101
  setRoute: (route: string) => Promise<void>;
100
102
  configLoader(config: Config.T<ParserParams>): Promise<void>;
101
103
  loadConfig: (config: Config.T<ParserParams>) => Promise<void>;
102
- addTranslations: (translations?: Translations.SerializedTranslations | undefined, keys?: Loader.IndexedKeys | undefined) => void;
103
104
  getTranslationProps: ($locale?: string, $route?: string) => Promise<[Translations.SerializedTranslations, Loader.IndexedKeys] | [
104
105
  ]>;
106
+ addTranslations: (translations?: Translations.SerializedTranslations | undefined, keys?: Loader.IndexedKeys | undefined) => void;
105
107
  private translationLoader;
106
108
  loadTranslations: (locale: Config.Locale, route?: string) => Promise<void>;
107
109
  }
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- var E=Object.defineProperty,O=Object.defineProperties;var z=Object.getOwnPropertyDescriptors;var b=Object.getOwnPropertySymbols;var R=Object.prototype.hasOwnProperty,S=Object.prototype.propertyIsEnumerable;var x=(r,t,e)=>t in r?E(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e,n=(r,t)=>{for(var e in t||(t={}))R.call(t,e)&&x(r,e,t[e]);if(b)for(var e of b(t))S.call(t,e)&&x(r,e,t[e]);return r},l=(r,t)=>O(r,z(t));var y=(r,t)=>{var e={};for(var a in r)R.call(r,a)&&t.indexOf(a)<0&&(e[a]=r[a]);if(r!=null&&b)for(var a of b(r))t.indexOf(a)<0&&S.call(r,a)&&(e[a]=r[a]);return e};import{derived as g,get as d,writable as m}from"svelte/store";var f=r=>{if(!r)return[];let t=r;return Array.isArray(t)||(t=[t]),t.map(e=>{let a=`${e}`.toLowerCase();try{[a]=Intl.Collator.supportedLocalesOf(e)}catch{console.warn("Unstandard locale provided! Check your `translations` and `loaders` in config...")}return a})},v=(r,t)=>Object.keys(r||{}).reduce((e,a)=>{let s=r[a],o=t?`${t}.${a}`:`${a}`;return s&&typeof s=="object"?n(n({},e),v(s,o)):l(n({},e),{[o]:s})},{}),F=async r=>{try{return(await Promise.all(r.map(s=>{var o=s,{loader:e}=o,a=y(o,["loader"]);return new Promise(async i=>{let h;try{h=await e()}catch(T){console.error(`Failed to load translation. Verify your '${a.locale}' > '${a.key}' Loader.`),console.error(T)}i(l(n({loader:e},a),{data:h}))})}))).reduce((e,{key:a,data:s,locale:o})=>{if(!s)return e;let i=f(o)[0];return l(n({},e),{[i]:v(l(n({},e[i]||{}),{[a]:s}))})},{})}catch(t){console.error(t)}return{}},$=r=>t=>{try{if(typeof t=="string")return t===r;if(typeof t=="object")return t.test(r)}catch{throw new Error("Invalid route config!")}return!1};var K=class{constructor(t){this.loadedKeys={};this.currentRoute=m();this.config=m();this.isLoading=m(!1);this.promises=[];this.loading={subscribe:this.isLoading.subscribe,toPromise:()=>Promise.all(this.promises),get:()=>d(this.isLoading)};this.privateTranslations=m({});this.translations={subscribe:this.privateTranslations.subscribe,get:()=>d(this.translations)};this.locales=l(n({},g([this.config,this.privateTranslations],([t,e])=>{if(!t)return[];let{loaders:a=[]}=t,s=a.map(({locale:i})=>f(i)[0]),o=Object.keys(e).map(i=>f(i)[0]);return[...new Set([...s,...o])]},[])),{get:()=>d(this.locales)});this.internalLocale=m();this.locale=l(n({set:this.internalLocale.set,update:this.internalLocale.update},g(this.internalLocale,(t,e)=>{let a=this.getLocale(t);a&&a!==this.locale.get()&&e(a)})),{get:()=>d(this.locale)});this.loaderTrigger=g([this.internalLocale,this.currentRoute],([t,e],a)=>{t!==void 0&&e!==void 0&&a([t,e])},[]);this.initialized=g([this.locale,this.currentRoute,this.privateTranslations],([t,e,a],s)=>{d(this.initialized)||s(t!==void 0&&e!==void 0&&!!Object.keys(a).length)});this.translation=g([this.privateTranslations,this.locale,this.isLoading],([t,e,a],s)=>{let o=t[e];o&&Object.keys(o).length&&!a&&s(o)},{});this.translate=({parser:t,key:e,params:a,translations:s,locale:o,fallbackLocale:i})=>{if(!(e&&o))return console.warn("No translation key or locale provided. Skipping translation..."),"";let h=(s[o]||{})[e];return i&&h===void 0&&(h=(s[i]||{})[e]),t.parse(h,a,o,e)};this.t=l(n({},g([this.config,this.translation],([{parser:t,fallbackLocale:e}])=>(a,...s)=>this.translate({parser:t,key:a,params:s,translations:this.translations.get(),locale:this.locale.get(),fallbackLocale:e}))),{get:(t,...e)=>d(this.t)(t,...e)});this.l=l(n({},g([this.config,this.translations],([{parser:t,fallbackLocale:e},a])=>(s,o,...i)=>this.translate({parser:t,key:o,params:i,translations:a,locale:s,fallbackLocale:e}))),{get:(t,e,...a)=>d(this.l)(t,e,...a)});this.getLocale=t=>{if(!t)return"";let a=this.locales.get().find(s=>`${f(s)}`==`${f(t)}`)||"";return`${f(a)}`};this.setLocale=async t=>{!t||(this.internalLocale.set(`${f(t)}`),await this.loading.toPromise())};this.setRoute=async t=>{t!==d(this.currentRoute)&&this.currentRoute.set(t),await this.loading.toPromise()};this.loadConfig=async t=>{await this.configLoader(t)};this.addTranslations=(t,e)=>{if(!t)return;let a=Object.keys(t||{});this.privateTranslations.update(s=>a.reduce((o,i)=>l(n({},o),{[i]:n(n({},o[i]||{}),v(t[i]))}),s)),a.forEach(s=>{let o=Object.keys(t[s]).map(i=>`${i}`.split(".")[0]);e&&(o=e[s]),this.loadedKeys[s]=Array.from(new Set([...this.loadedKeys[s]||[],...o||[]]))})};this.getTranslationProps=async(t=this.locale.get(),e=d(this.currentRoute))=>{let a=d(this.config);if(!a||!t)return[];let s=this.translations.get(),{loaders:o,fallbackLocale:i=""}=a||{},h=`${t}`.toLowerCase(),T=i&&`${i}`.toLowerCase(),j=s[h],k=s[T],w=(o||[]).map(C=>{var u=C,{locale:c}=u,p=y(u,["locale"]);return l(n({},p),{locale:`${c}`.toLowerCase()})}).filter(({routes:c})=>!c||(c||[]).some($(e))).filter(({key:c,locale:p})=>p===h&&(!j||!(this.loadedKeys[h]||[]).includes(c))||i&&p===T&&(!k||!(this.loadedKeys[T]||[]).includes(c)));if(w.length){this.isLoading.set(!0);let c=await F(w);this.isLoading.set(!1);let p=Object.keys(c).reduce((u,L)=>l(n({},u),{[L]:Object.keys(c[L])}),{}),C=w.filter(({key:u,locale:L})=>(p[L]||[]).some(P=>`${P}`.startsWith(u))).reduce((u,{key:L,locale:P})=>l(n({},u),{[P]:[...u[P]||[],L]}),{});return[c,C]}return[]};this.translationLoader=async t=>{this.promises.push(new Promise(async e=>{let a=await this.getTranslationProps(t);a.length&&this.addTranslations(...a),e()})),await this.loading.toPromise()};this.loadTranslations=async(t,e=d(this.currentRoute)||"")=>{!t||(this.setRoute(e),this.setLocale(t),await this.loading.toPromise())};t&&this.loadConfig(t),this.loaderTrigger.subscribe(()=>this.translationLoader())}async configLoader(t){if(!t)throw new Error("No config provided!");let i=t,{initLocale:e,fallbackLocale:a,translations:s}=i,o=y(i,["initLocale","fallbackLocale","translations"]);e=f(e)[0],a=f(a)[0],this.config.set(n({initLocale:e,fallbackLocale:a,translations:s},o)),s&&this.addTranslations(s),await this.loadTranslations(e)}};export{K as default};
1
+ var A=Object.defineProperty,W=Object.defineProperties;var D=Object.getOwnPropertyDescriptors;var P=Object.getOwnPropertySymbols;var F=Object.prototype.hasOwnProperty,K=Object.prototype.propertyIsEnumerable;var S=(r,t,e)=>t in r?A(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e,n=(r,t)=>{for(var e in t||(t={}))F.call(t,e)&&S(r,e,t[e]);if(P)for(var e of P(t))K.call(t,e)&&S(r,e,t[e]);return r},l=(r,t)=>W(r,D(t));var m=(r,t)=>{var e={};for(var s in r)F.call(r,s)&&t.indexOf(s)<0&&(e[s]=r[s]);if(r!=null&&P)for(var s of P(r))t.indexOf(s)<0&&K.call(r,s)&&(e[s]=r[s]);return e};import{derived as u,get as h,writable as y}from"svelte/store";var d=r=>{if(!r||!r.length)return[];let t=r;return Array.isArray(t)||(t=[t]),t.filter(e=>!!e).map(e=>{let s=`${e}`.toLowerCase();try{[s]=Intl.Collator.supportedLocalesOf(e)}catch{console.warn(`Non-standard locale provided: '${r}' => '${t}'. Check your 'translations' and 'loaders' in i18n config...`)}return s})},b=(r,t)=>Object.keys(r||{}).reduce((e,s)=>{let a=r[s],i=t?`${t}.${s}`:`${s}`;return a&&typeof a=="object"?n(n({},e),b(a,i)):l(n({},e),{[i]:a})},{}),N=async r=>{try{return(await Promise.all(r.map(a=>{var i=a,{loader:e}=i,s=m(i,["loader"]);return new Promise(async o=>{let f;try{f=await e()}catch(v){console.error(`Failed to load translation. Verify your '${s.locale}' > '${s.key}' Loader.`),console.error(v)}o(l(n({loader:e},s),{data:f}))})}))).reduce((e,{key:s,data:a,locale:i})=>{if(!a)return e;let o=d(i)[0];return l(n({},e),{[o]:b(l(n({},e[o]||{}),{[s]:a}))})},{})}catch(t){console.error(t)}return{}},j=r=>t=>{try{if(typeof t=="string")return t===r;if(typeof t=="object")return t.test(r)}catch{throw new Error("Invalid route config!")}return!1};var z=1e3*60*60*24,k=class{constructor(t){this.cachedAt=0;this.loadedKeys={};this.currentRoute=y();this.config=y();this.isLoading=y(!1);this.promises=[];this.loading={subscribe:this.isLoading.subscribe,toPromise:t=>t?this.promises[t]:Promise.all(this.promises),get:()=>h(this.isLoading)};this.privateTranslations=y({});this.translations={subscribe:this.privateTranslations.subscribe,get:()=>h(this.translations)};this.locales=l(n({},u([this.config,this.privateTranslations],([t,e])=>{if(!t)return[];let{loaders:s=[]}=t,a=s.map(({locale:o})=>d(o)[0]),i=Object.keys(e).map(o=>d(o)[0]);return[...new Set([...a,...i])]},[])),{get:()=>h(this.locales)});this.internalLocale=y();this.locale=l(n({set:this.internalLocale.set,update:this.internalLocale.update},u(this.internalLocale,(t,e)=>{let s=this.getLocale(t);s&&s!==this.locale.get()&&e(s)})),{get:()=>h(this.locale)});this.loaderTrigger=u([this.internalLocale,this.currentRoute],([t,e],s)=>{t!==void 0&&e!==void 0&&s([t,e])},[]);this.initialized=u([this.locale,this.currentRoute,this.privateTranslations],([t,e,s],a)=>{h(this.initialized)||a(t!==void 0&&e!==void 0&&!!Object.keys(s).length)});this.translation=u([this.privateTranslations,this.locale,this.isLoading],([t,e,s],a)=>{let i=t[e];i&&Object.keys(i).length&&!s&&a(i)},{});this.translate=({parser:t,key:e,params:s,translations:a,locale:i,fallbackLocale:o})=>{if(!(e&&i))return console.warn("No translation key or locale provided. Skipping translation..."),"";let f=(a[i]||{})[e];return o&&f===void 0&&(f=(a[o]||{})[e]),t.parse(f,s,i,e)};this.t=l(n({},u([this.config,this.translation],([{parser:t,fallbackLocale:e}])=>(s,...a)=>this.translate({parser:t,key:s,params:a,translations:this.translations.get(),locale:this.locale.get(),fallbackLocale:e}))),{get:(t,...e)=>h(this.t)(t,...e)});this.l=l(n({},u([this.config,this.translations],([{parser:t,fallbackLocale:e},s])=>(a,i,...o)=>this.translate({parser:t,key:i,params:o,translations:s,locale:a,fallbackLocale:e}))),{get:(t,e,...s)=>h(this.l)(t,e,...s)});this.getLocale=t=>{if(!t)return"";let s=this.locales.get().find(a=>a===d(t)[0])||"";return d(s)[0]||""};this.setLocale=async t=>{if(!t)return;let e=this.promises.length;this.internalLocale.set(d(t)[0]),await this.loading.toPromise(e)};this.setRoute=async t=>{let e=this.promises.length;t!==h(this.currentRoute)&&this.currentRoute.set(t),await this.loading.toPromise(e)};this.loadConfig=async t=>{await this.configLoader(t)};this.getTranslationProps=async(t=this.locale.get(),e=h(this.currentRoute))=>{let s=h(this.config);if(!s||!t)return[];let a=this.translations.get(),{loaders:i,fallbackLocale:o="",cache:f=z}=s||{},v=Number.isNaN(+f)?z:+f;this.cachedAt?Date.now()>v+this.cachedAt&&(this.loadedKeys={},this.cachedAt=0):this.cachedAt=Date.now();let[w,C]=d([t,o]),E=a[w],O=a[C],x=(i||[]).map(R=>{var g=R,{locale:c}=g,p=m(g,["locale"]);return l(n({},p),{locale:d(c)[0]})}).filter(({routes:c})=>!c||(c||[]).some(j(e))).filter(({key:c,locale:p})=>p===w&&(!E||!(this.loadedKeys[w]||[]).includes(c))||o&&p===C&&(!O||!(this.loadedKeys[C]||[]).includes(c)));if(x.length){this.isLoading.set(!0);let c=await N(x);this.isLoading.set(!1);let p=Object.keys(c).reduce((g,L)=>l(n({},g),{[L]:Object.keys(c[L])}),{}),R=x.filter(({key:g,locale:L})=>(p[L]||[]).some(T=>`${T}`.startsWith(g))).reduce((g,{key:L,locale:T})=>l(n({},g),{[T]:[...g[T]||[],L]}),{});return[c,R]}return[]};this.addTranslations=(t,e)=>{if(!t)return;let s=Object.keys(t||{});this.privateTranslations.update(a=>s.reduce((i,o)=>l(n({},i),{[o]:n(n({},i[o]||{}),b(t[o]))}),a)),s.forEach(a=>{let i=Object.keys(t[a]).map(o=>`${o}`.split(".")[0]);e&&(i=e[a]),this.loadedKeys[a]=Array.from(new Set([...this.loadedKeys[a]||[],...i||[]]))})};this.translationLoader=async t=>{let e=this.promises.length;this.promises.push(new Promise(async s=>{let a=await this.getTranslationProps(t);a.length&&this.addTranslations(...a),this.setLocale(t),s()})),await this.loading.toPromise(e)};this.loadTranslations=async(t,e=h(this.currentRoute)||"")=>{if(!t)return;let s=this.promises.length;this.setRoute(e),this.setLocale(t),await this.loading.toPromise(s)};t&&this.loadConfig(t),this.loaderTrigger.subscribe(([e])=>this.translationLoader(e)),this.isLoading.subscribe(async e=>{e&&(await this.loading.toPromise(),this.promises=[])})}async configLoader(t){if(!t)throw new Error("No config provided!");let o=t,{initLocale:e,fallbackLocale:s,translations:a}=o,i=m(o,["initLocale","fallbackLocale","translations"]);e=d(e)[0],s=d(s)[0],this.config.set(n({initLocale:e,fallbackLocale:s,translations:a},i)),a&&this.addTranslations(a),await this.loadTranslations(e)}};export{k as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sveltekit-i18n/base",
3
- "version": "1.0.0-rc.5",
3
+ "version": "1.0.0",
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",