@sveltekit-i18n/base 1.0.0-beta.6 → 1.0.0-rc.3

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,16 +3,18 @@
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 a base functionality of [sveltekit-i18n](https://github.com/sveltekit-i18n/lib) and provides support for external message parsers.
7
+
8
+ __IMPORTANT: THIS PACKAGE IS STILL IN DEVELOPMENT - API MAY VARY UNTIL 1.0.0__
7
9
 
8
10
  ## Key features
9
11
 
10
12
  ✅ SvelteKit ready\
11
13
  ✅ SSR support\
14
+ ✅ Custom parsers – you can use any message syntax you need\
12
15
  ✅ Custom data sources – no matter if you are using local files or remote API to get your translations\
13
16
  ✅ Module-based – your translations are loaded for visited pages only (and only once!)\
14
17
  ✅ Component-scoped translations – you can create multiple instances with custom definitions\
15
- ✅ Custom parsers – you can use any message syntax you need\
16
18
  ✅ TS support\
17
19
  ✅ No external dependencies
18
20
 
@@ -23,8 +25,8 @@ Setup `translations.js` in your lib folder...
23
25
  import i18n from '@sveltekit-i18n/base';
24
26
  import parser from '@sveltekit-i18n/parser-default'; // use your preferred parser (or create your own)
25
27
 
26
- /** @type {import('@sveltekit-i18n/base').Config} */
27
- export const config = ({
28
+ /** @namespace {import('@sveltekit-i18n/parser-default').Config} */
29
+ const config = ({
28
30
  parser: parser({}),
29
31
  loaders: [
30
32
  {
@@ -115,7 +117,12 @@ export const { t, locale, locales, loading, loadTranslations } = new i18n(config
115
117
  </div>
116
118
  ```
117
119
 
120
+
118
121
  ## More info
119
- [Docs](https://github.com/sveltekit-i18n/lib/tree/master/docs/README.md)\
120
- [Examples](https://github.com/sveltekit-i18n/lib/tree/master/examples)\
121
- [Changelog](https://github.com/sveltekit-i18n/lib/releases)
122
+ [Docs](https://github.com/sveltekit-i18n/base/tree/master/docs/README.md)\
123
+ [Examples](https://github.com/sveltekit-i18n/lib/tree/master/examples#parsers)\
124
+ [Changelog](https://github.com/sveltekit-i18n/base/releases)
125
+
126
+
127
+ ## Issues
128
+ If you are facing some issues related to the base functionality, create a ticket [here](https://github.com/sveltekit-i18n/lib/issues).
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- var P=Object.defineProperty,S=Object.defineProperties,O=Object.getOwnPropertyDescriptor,W=Object.getOwnPropertyDescriptors,K=Object.getOwnPropertyNames,m=Object.getOwnPropertySymbols;var w=Object.prototype.hasOwnProperty,C=Object.prototype.propertyIsEnumerable;var R=(a,t,e)=>t in a?P(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e,l=(a,t)=>{for(var e in t||(t={}))w.call(t,e)&&R(a,e,t[e]);if(m)for(var e of m(t))C.call(t,e)&&R(a,e,t[e]);return a},c=(a,t)=>S(a,W(t)),N=a=>P(a,"__esModule",{value:!0});var y=(a,t)=>{var e={};for(var s in a)w.call(a,s)&&t.indexOf(s)<0&&(e[s]=a[s]);if(a!=null&&m)for(var s of m(a))t.indexOf(s)<0&&C.call(a,s)&&(e[s]=a[s]);return e};var k=(a,t)=>{for(var e in t)P(a,e,{get:t[e],enumerable:!0})},D=(a,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of K(t))!w.call(a,r)&&(e||r!=="default")&&P(a,r,{get:()=>t[r],enumerable:!(s=O(t,r))||s.enumerable});return a};var z=(a=>(t,e)=>a&&a.get(t)||(e=D(N({}),t,1),a&&a.set(t,e),e))(typeof WeakMap!="undefined"?new WeakMap:0);var I={};k(I,{default:()=>A});var i=require("svelte/store");var T=(a,t)=>Object.keys(a||{}).reduce((e,s)=>{let r=a[s],o=t?`${t}.${s}`:`${s}`;return r&&typeof r=="object"?l(l({},e),T(r,o)):c(l({},e),{[o]:r})},{}),F=async a=>{try{return(await Promise.all(a.map(r=>{var o=r,{loader:e}=o,s=y(o,["loader"]);return new Promise(async n=>{let g;try{g=await e()}catch(p){console.error(`Failed to load translation. Verify your '${s.locale}' > '${s.key}' loader.`),console.error(p)}n(c(l({loader:e},s),{data:g}))})}))).reduce((e,{key:s,data:r,locale:o})=>r?c(l({},e),{[o]:T(c(l({},e[o]||{}),{[s]:r}))}):e,{})}catch(t){console.error(t)}return{}},x=a=>t=>{try{if(typeof t=="string")return t===a;if(typeof t=="object")return t.test(a)}catch{throw new Error("Invalid route config!")}return!1};var $=class{constructor(t){this.loadedKeys={};this.currentRoute=(0,i.writable)();this.config=(0,i.writable)();this.isLoading=(0,i.writable)(!1);this.promises=[];this.loading={subscribe:this.isLoading.subscribe,toPromise:()=>Promise.all(this.promises),get:()=>(0,i.get)(this.isLoading)};this.privateTranslations=(0,i.writable)({});this.translations={subscribe:this.privateTranslations.subscribe,get:()=>(0,i.get)(this.translations)};this.locales=c(l({},(0,i.derived)([this.config,this.privateTranslations],([t,e])=>{if(!t)return[];let{loaders:s=[]}=t,r=s.map(({locale:n})=>`${n}`.toLowerCase()),o=Object.keys(e).map(n=>`${n}`.toLowerCase());return[...new Set([...r,...o])]},[])),{get:()=>(0,i.get)(this.locales)});this.internalLocale=(0,i.writable)();this.locale=c(l({set:this.internalLocale.set,update:this.internalLocale.update},(0,i.derived)(this.internalLocale,(t,e)=>{let s=t&&`${t}`.toLowerCase(),r=this.getLocale(s);r&&r!==this.locale.get()&&e(r)})),{get:()=>(0,i.get)(this.locale)});this.loaderTrigger=(0,i.derived)([this.internalLocale,this.currentRoute],([t,e],s)=>{t!==void 0&&e!==void 0&&s([t,e])},[]);this.initialized=(0,i.derived)([this.locale,this.currentRoute,this.privateTranslations],([t,e,s],r)=>{(0,i.get)(this.initialized)||r(t!==void 0&&e!==void 0&&!!Object.keys(s).length)});this.translation=(0,i.derived)([this.privateTranslations,this.locale,this.isLoading],([t,e,s],r)=>{let o=t[e];o&&Object.keys(o).length&&!s&&r(o)},{});this.translate=({parser:t,key:e,params:s,translations:r,locale:o,fallbackLocale:n})=>{if(!e)throw new Error("No key provided to $t()");if(!o)throw new Error("No locale set!");let g=(r[o]||{})[e];return n&&g===void 0&&(g=(r[n]||{})[e]),t.parse(g,s,o,e)};this.t=c(l({},(0,i.derived)([this.config,this.translation],([{parser:t,fallbackLocale:e}])=>(s,...r)=>this.translate({parser:t,key:s,params:r,translations:this.translations.get(),locale:this.locale.get(),fallbackLocale:e}))),{get:(t,...e)=>(0,i.get)(this.t)(t,...e)});this.l=c(l({},(0,i.derived)([this.config,this.translations],([{parser:t,fallbackLocale:e},s])=>(r,o,...n)=>this.translate({parser:t,key:o,params:n,translations:s,locale:r,fallbackLocale:e}))),{get:(t,e,...s)=>(0,i.get)(this.l)(t,e,...s)});this.getLocale=t=>t?`${this.locales.get().find(r=>`${r}`.toLowerCase()===`${t}`.toLowerCase())||""}`.toLowerCase():"";this.setLocale=async t=>{!t||(this.internalLocale.set(t),await this.loading.toPromise())};this.setRoute=async t=>{t!==(0,i.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 s=Object.keys(t||{});this.privateTranslations.update(r=>s.reduce((o,n)=>c(l({},o),{[n]:l(l({},o[n]||{}),T(t[n]))}),r)),s.forEach(r=>{let o=Object.keys(t[r]).map(n=>`${n}`.split(".")[0]);e&&(o=e[r]),this.loadedKeys[r]=Array.from(new Set([...this.loadedKeys[r]||[],...o||[]]))})};this.getTranslationProps=async(t=this.locale.get(),e=(0,i.get)(this.currentRoute))=>{let s=(0,i.get)(this.config);if(!s||!t)return[];let r=this.translations.get(),{loaders:o,fallbackLocale:n=""}=s||{},g=`${t}`.toLowerCase(),p=n&&`${n}`.toLowerCase(),E=r[g],j=r[p],b=(o||[]).map(v=>{var h=v,{locale:d}=h,u=y(h,["locale"]);return c(l({},u),{locale:`${d}`.toLowerCase()})}).filter(({routes:d})=>!d||(d||[]).some(x(e))).filter(({key:d,locale:u})=>u===g&&(!E||!(this.loadedKeys[g]||[]).includes(d))||n&&u===p&&(!j||!(this.loadedKeys[p]||[]).includes(d)));if(b.length){this.isLoading.set(!0);let d=await F(b);this.isLoading.set(!1);let u=Object.keys(d).reduce((h,f)=>c(l({},h),{[f]:Object.keys(d[f])}),{}),v=b.filter(({key:h,locale:f})=>(u[f]||[]).some(L=>`${L}`.startsWith(h))).reduce((h,{key:f,locale:L})=>c(l({},h),{[L]:[...h[L]||[],f]}),{});return[d,v]}return[]};this.translationLoader=async t=>{this.promises.push(new Promise(async e=>{let s=await this.getTranslationProps(t);s.length&&this.addTranslations(...s),e()})),await this.loading.toPromise()};this.loadTranslations=async(t,e=(0,i.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!");this.config.set(t);let{initLocale:e="",translations:s}=t;s&&this.addTranslations(s),await this.loadTranslations(e)}};var A=$;module.exports=z(I);0&&(module.exports={});
1
+ var P=Object.defineProperty,E=Object.defineProperties,O=Object.getOwnPropertyDescriptor,K=Object.getOwnPropertyDescriptors,W=Object.getOwnPropertyNames,m=Object.getOwnPropertySymbols;var w=Object.prototype.hasOwnProperty,S=Object.prototype.propertyIsEnumerable;var x=(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)&&x(r,e,t[e]);if(m)for(var e of m(t))S.call(t,e)&&x(r,e,t[e]);return r},c=(r,t)=>E(r,K(t)),N=r=>P(r,"__esModule",{value:!0});var y=(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 z=(r,t)=>{for(var e in t)P(r,e,{get:t[e],enumerable:!0})},D=(r,t,e,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of W(t))!w.call(r,s)&&(e||s!=="default")&&P(r,s,{get:()=>t[s],enumerable:!(a=O(t,s))||a.enumerable});return r};var A=(r=>(t,e)=>r&&r.get(t)||(e=D(N({}),t,1),r&&r.set(t,e),e))(typeof WeakMap!="undefined"?new WeakMap:0);var M={};z(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=y(o,["loader"]);return new Promise(async i=>{let g;try{g=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:g}))})}))).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 g=(s[o]||{})[e];return i&&g===void 0&&(g=(s[i]||{})[e]),t.parse(g,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||{},g=`${t}`.toLowerCase(),L=i&&`${i}`.toLowerCase(),j=s[g],k=s[L],v=(o||[]).map(R=>{var u=R,{locale:d}=u,h=y(u,["locale"]);return c(l({},h),{locale:`${d}`.toLowerCase()})}).filter(({routes:d})=>!d||(d||[]).some($(e))).filter(({key:d,locale:h})=>h===g&&(!j||!(this.loadedKeys[g]||[]).includes(d))||i&&h===L&&(!k||!(this.loadedKeys[L]||[]).includes(d)));if(v.length){this.isLoading.set(!0);let d=await F(v);this.isLoading.set(!1);let h=Object.keys(d).reduce((u,p)=>c(l({},u),{[p]:Object.keys(d[p])}),{}),R=v.filter(({key:u,locale:p})=>(h[p]||[]).some(T=>`${T}`.startsWith(u))).reduce((u,{key:p,locale:T})=>c(l({},u),{[T]:[...u[T]||[],p]}),{});return[d,R]}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=y(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=A(M);0&&(module.exports={});
package/dist/index.d.ts CHANGED
@@ -1,51 +1,77 @@
1
1
  import { Readable, Writable } from 'svelte/store';
2
2
 
3
- type LoadingStore = Readable<boolean> & { toPromise: () => Promise<void[]>, get: () => boolean };
4
-
5
- type Loader = () => Promise<Record<any, any>>;
6
-
7
- type Route = string | RegExp;
8
-
9
- type LoaderModule = {
10
- key: string;
11
- locale: string;
12
- routes?: Route[];
13
- loader: Loader;
14
- };
15
-
16
- type ParserParamsDefault = any[] | [];
17
-
18
- type TranslationFunction<ParserParams extends ParserParamsDefault> = (key: string, ...restParams: ParserParams) => string;
19
-
20
- type LocalTranslationFunction<ParserParams extends ParserParamsDefault> = (locale: string, key: string, ...restParams: ParserParams) => string;
21
-
22
- type ExtendedStore<T, Get = () => T, Store = Readable<T>> = Store & { get: Get };
23
-
24
- type ConfigTranslations = { [locale: string]: Record<string, any> };
25
-
26
- type Translations = { [locale: string]: Record<string, string> };
27
-
28
- type Parse<ParserParams = ParserParamsDefault> = (
29
- text: string | undefined,
30
- params: ParserParams,
31
- locale: string,
32
- key: string,
33
- ) => string;
34
-
35
- type Parser<ParserParams = ParserParamsDefault> = {
36
- parse: Parse<ParserParams>;
3
+ declare type ExtendedStore<T, Get = () => T, Store = Readable<T>> = Store & {
4
+ get: Get;
37
5
  };
38
-
39
- type Config<ParserParams = ParserParamsDefault> = {
40
- loaders?: LoaderModule[];
41
- translations?: ConfigTranslations;
42
- initLocale?: string;
43
- fallbackLocale?: string;
44
- parser: Parser<ParserParams>;
6
+ declare type LoadingStore = Readable<boolean> & {
7
+ toPromise: () => Promise<void[]>;
8
+ get: () => boolean;
45
9
  };
10
+ declare module DotNotation {
11
+ type Input = any;
12
+ type Output<V = any, K extends keyof V = keyof V> = {
13
+ [P in K]?: V[K];
14
+ } | null;
15
+ type T = <I = Input>(input: I, parentKey?: string) => Output<I>;
16
+ }
17
+ declare module Config {
18
+ type Loaders = Loader.LoaderModule[] | undefined;
19
+ type Translations = Translations.T | undefined;
20
+ type Locale = string;
21
+ type InitLocale = Locale | undefined;
22
+ type FallbackLocale = Locale | undefined;
23
+ type T<P extends Parser.Params = Parser.Params> = {
24
+ loaders?: Loaders;
25
+ translations?: Translations;
26
+ initLocale?: InitLocale;
27
+ fallbackLocale?: FallbackLocale;
28
+ parser: Parser.T<P>;
29
+ };
30
+ }
31
+ declare module Loader {
32
+ type Key = string;
33
+ type Locale = Config.Locale;
34
+ type Route = string | RegExp;
35
+ type LoaderModule = {
36
+ key: Key;
37
+ locale: Locale;
38
+ routes?: Route[];
39
+ loader: T;
40
+ };
41
+ type T = () => Promise<Record<any, any>>;
42
+ }
43
+ declare module Parser {
44
+ type Value = any;
45
+ type Params = Array<unknown>;
46
+ type Locale = Config.Locale;
47
+ type Key = Loader.Key;
48
+ type Output = any;
49
+ type Parse<P extends Parser.Params = Parser.Params> = (value: Value, params: P, locale: Locale, key: Key) => Output;
50
+ type ParserFactory<ParserConfig = any, P extends Parser.Params = any> = (config?: ParserConfig) => Parser.T<P>;
51
+ type T<P extends Parser.Params = Parser.Params> = {
52
+ parse: Parse<P>;
53
+ };
54
+ }
55
+ declare module Translations {
56
+ type SerializedTranslations = T<DotNotation.Output>;
57
+ type FetchTranslations = (loaders: Loader.LoaderModule[]) => Promise<SerializedTranslations>;
58
+ type TranslationFunction<P extends Parser.Params = Parser.Params> = (key: string, ...restParams: P) => string;
59
+ type LocalTranslationFunction<P extends Parser.Params = Parser.Params> = (locale: string, key: string, ...restParams: P) => string;
60
+ type Translate<P extends Parser.Params = Parser.Params> = (props: {
61
+ parser: Parser.T<P>;
62
+ key: string;
63
+ params: P;
64
+ translations: SerializedTranslations;
65
+ locale: string;
66
+ fallbackLocale?: string;
67
+ }) => string;
68
+ type T<V = any> = {
69
+ [locale: string]: Record<string, V>;
70
+ };
71
+ }
46
72
 
47
- declare class I18n<ParserParams extends ParserParamsDefault> {
48
- constructor(config?: Config<ParserParams>);
73
+ declare class I18n<ParserParams extends Parser.Params = any> {
74
+ constructor(config?: Config.T<ParserParams>);
49
75
  private loadedKeys;
50
76
  private currentRoute;
51
77
  private config;
@@ -53,26 +79,26 @@ declare class I18n<ParserParams extends ParserParamsDefault> {
53
79
  private promises;
54
80
  loading: LoadingStore;
55
81
  private privateTranslations;
56
- translations: ExtendedStore<Translations>;
57
- locales: ExtendedStore<string[]>;
82
+ translations: ExtendedStore<Translations.SerializedTranslations>;
83
+ locales: ExtendedStore<Config.Locale[]>;
58
84
  private internalLocale;
59
- locale: ExtendedStore<string, () => string, Writable<string>>;
85
+ locale: ExtendedStore<Config.Locale, () => Config.Locale, Writable<string>>;
60
86
  private loaderTrigger;
61
87
  initialized: Readable<boolean>;
62
88
  private translation;
63
89
  private translate;
64
- t: ExtendedStore<TranslationFunction<ParserParams>, TranslationFunction<ParserParams>>;
65
- l: ExtendedStore<LocalTranslationFunction<ParserParams>, LocalTranslationFunction<ParserParams>>;
90
+ t: ExtendedStore<Translations.TranslationFunction<ParserParams>, Translations.TranslationFunction<ParserParams>>;
91
+ l: ExtendedStore<Translations.LocalTranslationFunction<ParserParams>, Translations.LocalTranslationFunction<ParserParams>>;
66
92
  private getLocale;
67
93
  setLocale: (locale?: string | undefined) => Promise<void>;
68
94
  setRoute: (route: string) => Promise<void>;
69
- configLoader(config: Config<ParserParams>): Promise<void>;
70
- loadConfig: (config: Config<ParserParams>) => Promise<void>;
71
- addTranslations: (translations?: ConfigTranslations | undefined, keys?: Record<string, string[]> | undefined) => void;
72
- getTranslationProps: ($locale?: string, $route?: string) => Promise<[ConfigTranslations, Record<string, string[]>] | [
95
+ configLoader(config: Config.T<ParserParams>): Promise<void>;
96
+ loadConfig: (config: Config.T<ParserParams>) => Promise<void>;
97
+ addTranslations: (translations?: Config.Translations, keys?: Record<string, string[]> | undefined) => void;
98
+ getTranslationProps: ($locale?: string, $route?: string) => Promise<[Config.Translations, Record<string, string[]>] | [
73
99
  ]>;
74
100
  private translationLoader;
75
- loadTranslations: (locale: string, route?: string) => Promise<void>;
101
+ loadTranslations: (locale: Config.Locale, route?: string) => Promise<void>;
76
102
  }
77
103
 
78
- export { Config, Parse, Parser, I18n as default };
104
+ export { Config, Loader, Parser, Translations, I18n as default };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- var O=Object.defineProperty,W=Object.defineProperties;var K=Object.getOwnPropertyDescriptors;var y=Object.getOwnPropertySymbols;var C=Object.prototype.hasOwnProperty,F=Object.prototype.propertyIsEnumerable;var R=(o,t,e)=>t in o?O(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e,n=(o,t)=>{for(var e in t||(t={}))C.call(t,e)&&R(o,e,t[e]);if(y)for(var e of y(t))F.call(t,e)&&R(o,e,t[e]);return o},l=(o,t)=>W(o,K(t));var T=(o,t)=>{var e={};for(var s in o)C.call(o,s)&&t.indexOf(s)<0&&(e[s]=o[s]);if(o!=null&&y)for(var s of y(o))t.indexOf(s)<0&&F.call(o,s)&&(e[s]=o[s]);return e};import{derived as u,get as d,writable as m}from"svelte/store";var b=(o,t)=>Object.keys(o||{}).reduce((e,s)=>{let r=o[s],a=t?`${t}.${s}`:`${s}`;return r&&typeof r=="object"?n(n({},e),b(r,a)):l(n({},e),{[a]:r})},{}),x=async o=>{try{return(await Promise.all(o.map(r=>{var a=r,{loader:e}=a,s=T(a,["loader"]);return new Promise(async i=>{let g;try{g=await e()}catch(L){console.error(`Failed to load translation. Verify your '${s.locale}' > '${s.key}' loader.`),console.error(L)}i(l(n({loader:e},s),{data:g}))})}))).reduce((e,{key:s,data:r,locale:a})=>r?l(n({},e),{[a]:b(l(n({},e[a]||{}),{[s]:r}))}):e,{})}catch(t){console.error(t)}return{}},$=o=>t=>{try{if(typeof t=="string")return t===o;if(typeof t=="object")return t.test(o)}catch{throw new Error("Invalid route config!")}return!1};var E=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({},u([this.config,this.privateTranslations],([t,e])=>{if(!t)return[];let{loaders:s=[]}=t,r=s.map(({locale:i})=>`${i}`.toLowerCase()),a=Object.keys(e).map(i=>`${i}`.toLowerCase());return[...new Set([...r,...a])]},[])),{get:()=>d(this.locales)});this.internalLocale=m();this.locale=l(n({set:this.internalLocale.set,update:this.internalLocale.update},u(this.internalLocale,(t,e)=>{let s=t&&`${t}`.toLowerCase(),r=this.getLocale(s);r&&r!==this.locale.get()&&e(r)})),{get:()=>d(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],r)=>{d(this.initialized)||r(t!==void 0&&e!==void 0&&!!Object.keys(s).length)});this.translation=u([this.privateTranslations,this.locale,this.isLoading],([t,e,s],r)=>{let a=t[e];a&&Object.keys(a).length&&!s&&r(a)},{});this.translate=({parser:t,key:e,params:s,translations:r,locale:a,fallbackLocale:i})=>{if(!e)throw new Error("No key provided to $t()");if(!a)throw new Error("No locale set!");let g=(r[a]||{})[e];return i&&g===void 0&&(g=(r[i]||{})[e]),t.parse(g,s,a,e)};this.t=l(n({},u([this.config,this.translation],([{parser:t,fallbackLocale:e}])=>(s,...r)=>this.translate({parser:t,key:s,params:r,translations:this.translations.get(),locale:this.locale.get(),fallbackLocale:e}))),{get:(t,...e)=>d(this.t)(t,...e)});this.l=l(n({},u([this.config,this.translations],([{parser:t,fallbackLocale:e},s])=>(r,a,...i)=>this.translate({parser:t,key:a,params:i,translations:s,locale:r,fallbackLocale:e}))),{get:(t,e,...s)=>d(this.l)(t,e,...s)});this.getLocale=t=>t?`${this.locales.get().find(r=>`${r}`.toLowerCase()===`${t}`.toLowerCase())||""}`.toLowerCase():"";this.setLocale=async t=>{!t||(this.internalLocale.set(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 s=Object.keys(t||{});this.privateTranslations.update(r=>s.reduce((a,i)=>l(n({},a),{[i]:n(n({},a[i]||{}),b(t[i]))}),r)),s.forEach(r=>{let a=Object.keys(t[r]).map(i=>`${i}`.split(".")[0]);e&&(a=e[r]),this.loadedKeys[r]=Array.from(new Set([...this.loadedKeys[r]||[],...a||[]]))})};this.getTranslationProps=async(t=this.locale.get(),e=d(this.currentRoute))=>{let s=d(this.config);if(!s||!t)return[];let r=this.translations.get(),{loaders:a,fallbackLocale:i=""}=s||{},g=`${t}`.toLowerCase(),L=i&&`${i}`.toLowerCase(),j=r[g],S=r[L],w=(a||[]).map(v=>{var h=v,{locale:c}=h,f=T(h,["locale"]);return l(n({},f),{locale:`${c}`.toLowerCase()})}).filter(({routes:c})=>!c||(c||[]).some($(e))).filter(({key:c,locale:f})=>f===g&&(!j||!(this.loadedKeys[g]||[]).includes(c))||i&&f===L&&(!S||!(this.loadedKeys[L]||[]).includes(c)));if(w.length){this.isLoading.set(!0);let c=await x(w);this.isLoading.set(!1);let f=Object.keys(c).reduce((h,p)=>l(n({},h),{[p]:Object.keys(c[p])}),{}),v=w.filter(({key:h,locale:p})=>(f[p]||[]).some(P=>`${P}`.startsWith(h))).reduce((h,{key:p,locale:P})=>l(n({},h),{[P]:[...h[P]||[],p]}),{});return[c,v]}return[]};this.translationLoader=async t=>{this.promises.push(new Promise(async e=>{let s=await this.getTranslationProps(t);s.length&&this.addTranslations(...s),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!");this.config.set(t);let{initLocale:e="",translations:s}=t;s&&this.addTranslations(s),await this.loadTranslations(e)}};var I=E;export{I as default};
1
+ var O=Object.defineProperty,K=Object.defineProperties;var W=Object.getOwnPropertyDescriptors;var b=Object.getOwnPropertySymbols;var x=Object.prototype.hasOwnProperty,S=Object.prototype.propertyIsEnumerable;var R=(r,t,e)=>t in r?O(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e,n=(r,t)=>{for(var e in t||(t={}))x.call(t,e)&&R(r,e,t[e]);if(b)for(var e of b(t))S.call(t,e)&&R(r,e,t[e]);return r},l=(r,t)=>K(r,W(t));var T=(r,t)=>{var e={};for(var a in r)x.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 h,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=T(o,["loader"]);return new Promise(async i=>{let g;try{g=await e()}catch(y){console.error(`Failed to load translation. Verify your '${a.locale}' > '${a.key}' Loader.`),console.error(y)}i(l(n({loader:e},a),{data:g}))})}))).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 j=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({},h([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},h(this.internalLocale,(t,e)=>{let a=this.getLocale(t);a&&a!==this.locale.get()&&e(a)})),{get:()=>d(this.locale)});this.loaderTrigger=h([this.internalLocale,this.currentRoute],([t,e],a)=>{t!==void 0&&e!==void 0&&a([t,e])},[]);this.initialized=h([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=h([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 g=(s[o]||{})[e];return i&&g===void 0&&(g=(s[i]||{})[e]),t.parse(g,a,o,e)};this.t=l(n({},h([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({},h([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||{},g=`${t}`.toLowerCase(),y=i&&`${i}`.toLowerCase(),k=s[g],E=s[y],w=(o||[]).map(C=>{var u=C,{locale:c}=u,p=T(u,["locale"]);return l(n({},p),{locale:`${c}`.toLowerCase()})}).filter(({routes:c})=>!c||(c||[]).some($(e))).filter(({key:c,locale:p})=>p===g&&(!k||!(this.loadedKeys[g]||[]).includes(c))||i&&p===y&&(!E||!(this.loadedKeys[y]||[]).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=T(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{j as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sveltekit-i18n/base",
3
- "version": "1.0.0-beta.6",
3
+ "version": "1.0.0-rc.3",
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",
@@ -15,10 +15,10 @@
15
15
  "./package.json": "./package.json"
16
16
  },
17
17
  "scripts": {
18
- "dev": "tsup src/index.ts --dts --format cjs,esm --sourcemap --watch",
18
+ "dev": "tsup --watch",
19
19
  "test": "jest",
20
- "build": "tsup src/index.ts --dts --format cjs,esm --minify",
21
- "prepublishOnly": "rm -rf dist && npm run build",
20
+ "build": "tsup",
21
+ "prepublishOnly": "npm run build",
22
22
  "lint": "eslint --fix --ext .ts,.js --ignore-path .gitignore ."
23
23
  },
24
24
  "files": [
@@ -47,7 +47,10 @@
47
47
  },
48
48
  "homepage": "https://github.com/sveltekit-i18n/base#readme",
49
49
  "peerDependencies": {
50
- "svelte": "^3.44.3"
50
+ "svelte": "^3.x"
51
+ },
52
+ "optionalDependencies": {
53
+ "@sveltekit-i18n/parser-default": "^1.x"
51
54
  },
52
55
  "devDependencies": {
53
56
  "@types/jest": "^27.0.3",
@@ -56,12 +59,10 @@
56
59
  "eslint": "^8.4.1",
57
60
  "eslint-config-airbnb-typescript": "^16.1.0",
58
61
  "eslint-plugin-import": "^2.25.3",
59
- "eslint-plugin-svelte3": "^3.2.1",
60
62
  "jest": "^27.4.5",
61
63
  "pre-commit": "^1.2.2",
62
- "svelte": "^3.44.3",
63
64
  "ts-jest": "^27.1.2",
64
65
  "tsup": "^5.11.13",
65
66
  "typescript": "^4.5.4"
66
67
  }
67
- }
68
+ }