@arc-js/config-manager 0.0.1 → 0.0.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/config.min.js CHANGED
@@ -1,2 +1,2 @@
1
- var hasRequiredTimez,hasRequiredCooks,cooks={},timez={};function requireTimez(){if(!hasRequiredTimez){hasRequiredTimez=1,Object.defineProperty(timez,"__esModule",{value:!0});class f{constructor(e,t=!1){!1===this.dateChecker(e)?this._date=void 0:e instanceof f&&e&&null!=e&&e._date?this._date=new Date(null==e?void 0:e._date):e instanceof Date?this._date=new Date(e):"string"==typeof e?this._date=f.parseString(e,t):"number"==typeof e?this._date=new Date(e):null==e||"number"==typeof e&&isNaN(e)?this._date=new Date:this._date=void 0}static now(){return new f}static parse(e,t){return"string"==typeof t&&0<t.length&&(e instanceof f&&e&&null!=e&&e._date||e instanceof Date||"string"==typeof e||"number"==typeof e||null==e||"number"==typeof e&&isNaN(e))&&f.parseWithFormat(e,t)||new f(e)}static unix(e){return new f(1e3*e)}static utc(){var e=new Date;return new f(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds(),e.getUTCMilliseconds()))}year(){var e;return null==(e=this._date)?void 0:e.getFullYear()}month(){return this._date?this._date.getMonth()+1:void 0}date(){var e;return null==(e=this._date)?void 0:e.getDate()}hour(){var e;return null==(e=this._date)?void 0:e.getHours()}minute(){var e;return null==(e=this._date)?void 0:e.getMinutes()}second(){var e;return null==(e=this._date)?void 0:e.getSeconds()}millisecond(){var e;return null==(e=this._date)?void 0:e.getMilliseconds()}day(){var e;return null==(e=this._date)?void 0:e.getDay()}add(e,t){if(!this._date)return new f(void 0);var a=new Date(this._date);switch(t){case"years":a.setFullYear(a.getFullYear()+e);break;case"months":a.setMonth(a.getMonth()+e);break;case"days":a.setDate(a.getDate()+e);break;case"hours":a.setHours(a.getHours()+e);break;case"minutes":a.setMinutes(a.getMinutes()+e);break;case"seconds":a.setSeconds(a.getSeconds()+e);break;case"milliseconds":a.setMilliseconds(a.getMilliseconds()+e)}return new f(a)}subtract(e,t){return this.add(-e,t)}startOf(e){if(!this._date)return new f(void 0);var t=new Date(this._date);switch(e){case"year":t.setMonth(0,1),t.setHours(0,0,0,0);break;case"month":t.setDate(1),t.setHours(0,0,0,0);break;case"day":t.setHours(0,0,0,0);break;case"hour":t.setMinutes(0,0,0);break;case"minute":t.setSeconds(0,0);break;case"second":t.setMilliseconds(0)}return new f(t)}endOf(e){var t=this.startOf(e);switch(e){case"year":return t.add(1,"years").subtract(1,"milliseconds");case"month":return t.add(1,"months").subtract(1,"milliseconds");case"day":return t.add(1,"days").subtract(1,"milliseconds");case"hour":return t.add(1,"hours").subtract(1,"milliseconds");case"minute":return t.add(1,"minutes").subtract(1,"milliseconds");case"second":return t.add(1,"seconds").subtract(1,"milliseconds");default:return t}}isBefore(e,t="()"){t="]"===t[1],e=e instanceof f?e:new f(e);return!(!this._date||!e._date)&&(!t&&this._date<e._date||!!t&&this._date<=e._date)}isAfter(e,t="()"){t="["===t[0],e=e instanceof f?e:new f(e);return!(!this._date||!e._date)&&(!t&&this._date>e._date||!!t&&this._date>=e._date)}isSame(e,t){var a,e=e instanceof f?e:new f(e);return!t&&this._date&&e._date?this._date.getTime()===e._date.getTime():(a=t?this.startOf(t):void 0,e=t?e.startOf(t):void 0,!!(a&&null!=a&&a._date&&e&&null!=e&&e._date)&&a._date.getTime()===e._date.getTime())}isBetween(e,t,a="()"){var e=e instanceof f?e:new f(e),t=t instanceof f?t:new f(t),i="["===a[0],a="]"===a[1],i=i&&this.isSame(e)||this.isAfter(e),e=a&&this.isSame(t)||this.isBefore(t);return i&&e}format(e){if(!e)return this.toISOString();var t,a,i=f.PREDEFINED_FORMATS[e];if(i)return this.format(i);let r="",s=0;for(;s<e.length;)"["===e[s]?-1===(a=e.indexOf("]",s))?(r+=e[s],s++):(t=e.substring(s+1,a),r+=t,s=a+1):"%"===e[s]&&s+1<e.length?(t="%"+e[s+1],a=f.FORMAT_TOKENS[t],r+=a?a(this):t,s+=2):(r+=e[s],s++);return r}setTimezone(e){var t;return this._date?(t=this._date.getTimezoneOffset(),e=this.parseTimezoneOffset(e),e=new Date(this._date.getTime()+6e4*(e-t)),new f(e)):new f(void 0)}utc(){return this._date?new f(new Date(Date.UTC(this._date.getUTCFullYear(),this._date.getUTCMonth(),this._date.getUTCDate(),this._date.getUTCHours(),this._date.getUTCMinutes(),this._date.getUTCSeconds(),this._date.getUTCMilliseconds()))):new f(void 0)}local(){return this._date?new f(new Date(this._date.getFullYear(),this._date.getMonth(),this._date.getDate(),this._date.getHours(),this._date.getMinutes(),this._date.getSeconds(),this._date.getMilliseconds())):new f(void 0)}toString(){var e;return null==(e=this._date)?void 0:e.toString()}toISOString(){var e;return null==(e=this._date)?void 0:e.toISOString()}toDate(){return this._date?new Date(this._date):void 0}valueOf(){var e;return null==(e=this._date)?void 0:e.getTime()}unix(){return this._date?Math.floor(this._date.getTime()/1e3):void 0}utcOffset(){return this._date?-this._date.getTimezoneOffset():void 0}isCorrect(){return!!this._date&&!isNaN(this._date.getTime())}timezone(){if(this._date)try{return(new Intl.DateTimeFormat).resolvedOptions().timeZone||void 0}catch(e){return this.timezoneFromOffset()}}timezoneAbbr(){if(this._date)try{var e=new Intl.DateTimeFormat("en",{timeZoneName:"short"}).formatToParts(this._date).find(e=>"timeZoneName"===e.type);return(null==e?void 0:e.value)||void 0}catch(e){return this.timezoneAbbrFromOffset()}}timezoneName(){if(this._date)try{var e=new Intl.DateTimeFormat("en",{timeZoneName:"long"}).formatToParts(this._date).find(e=>"timeZoneName"===e.type);return(null==e?void 0:e.value)||void 0}catch(e){return this.timezoneNameFromOffset()}}timezoneOffsetString(){var e=this.utcOffset();if(void 0!==e)return(0<=e?"+":"-")+Math.floor(Math.abs(e)/60).toString().padStart(2,"0")+":"+(Math.abs(e)%60).toString().padStart(2,"0")}dateChecker(e){return e instanceof f&&!!e&&!(null==e||!e._date)||e instanceof Date||"string"==typeof e||"number"==typeof e||null==e||"number"==typeof e&&isNaN(e)}timezoneFromOffset(){var e=this.utcOffset();if(void 0!==e)return{0:"Etc/UTC",60:"Europe/Paris",120:"Europe/Athens",180:"Europe/Moscow",240:"Asia/Dubai",270:"Asia/Tehran",300:"Asia/Karachi",330:"Asia/Kolkata",345:"Asia/Rangoon",360:"Asia/Dhaka",390:"Asia/Yangon",420:"Asia/Bangkok",480:"Asia/Shanghai",525:"Asia/Kathmandu",540:"Asia/Tokyo",570:"Australia/Adelaide",600:"Australia/Sydney",630:"Australia/Lord_Howe",660:"Pacific/Noumea",675:"Australia/Eucla",720:"Pacific/Auckland",780:"Pacific/Chatham","-60":"Atlantic/Azores","-120":"America/Noronha","-180":"America/Argentina/Buenos_Aires","-210":"America/St_Johns","-240":"America/Halifax","-270":"America/Caracas","-300":"America/New_York","-360":"America/Chicago","-420":"America/Denver","-480":"America/Los_Angeles","-540":"America/Anchorage","-600":"Pacific/Honolulu","-660":"Pacific/Pago_Pago","-720":"Pacific/Kiritimati"}[e]||"Etc/GMT"+(0<=e?"-":"+")+Math.abs(e)/60}timezoneAbbrFromOffset(){var e=this.utcOffset();if(void 0!==e)return{0:"GMT",60:"CET","-300":"EST","-360":"CST","-420":"MST","-480":"PST"}[e]||"GMT"+(0<=e?"+":"")+e/60}timezoneNameFromOffset(){var e=this.utcOffset();if(void 0!==e)return{0:"Greenwich Mean Time",60:"Central European Time","-300":"Eastern Standard Time","-360":"Central Standard Time","-420":"Mountain Standard Time","-480":"Pacific Standard Time"}[e]||"GMT"+(0<=e?"+":"")+e/60}isDST(){if(this._date)try{var e=new Date(this._date.getFullYear(),0,1),t=new Date(this._date.getFullYear(),6,1),a=Math.max(e.getTimezoneOffset(),t.getTimezoneOffset());return this._date.getTimezoneOffset()<a}catch(e){}}static parseString(e,t=!1){var a=new Date(e);if(!isNaN(a.getTime()))return a;var i,r=[/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.(\d{3})Z$/,/^(\d{4})-(\d{2})-(\d{2})$/,/^(\d{4})\/(\d{2})\/(\d{2}) (\d{2}):(\d{2}):(\d{2})$/,/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/];for(i of r){var s=e.match(i);if(s){s=s.slice(1).map(Number);if(i===r[0])return new Date(Date.UTC(s[0],s[1]-1,s[2],s[3],s[4],s[5],s[6]));if(i===r[1])return new Date(s[0],s[1]-1,s[2]);if(i===r[2])return new Date(s[0],s[1]-1,s[2],s[3],s[4],s[5]);if(i===r[3])return new Date(s[0],s[1]-1,s[2],s[3],s[4],s[5])}}a=new Date(e);if(!isNaN(a.getTime()))return a;if(t)throw new Error("Unable to parse date string: "+e)}static parseWithFormat(e,r){if(e&&r){var s=String(e).trim();if(s){var n={Y:{regex:/\d{4}/,extract:e=>parseInt(e,10)},y:{regex:/\d{2}/,extract:e=>{e=parseInt(e,10);return 70<=e?1900+e:2e3+e}},m:{regex:/\d{1,2}/,extract:e=>parseInt(e,10)},d:{regex:/\d{1,2}/,extract:e=>parseInt(e,10)},H:{regex:/\d{1,2}/,extract:e=>parseInt(e,10)},M:{regex:/\d{1,2}/,extract:e=>parseInt(e,10)},S:{regex:/\d{1,2}/,extract:e=>parseInt(e,10)},f:{regex:/\d{1,3}/,extract:e=>parseInt(e,10)}},o={year:(new Date).getFullYear(),month:1,day:1,hour:0,minute:0,second:0,millisecond:0};let e=0,t=0,a=!1,i="";for(;t<r.length&&e<s.length;){var d=r[t];if("["===d)a=!0,i="",t++;else if("]"===d&&a){if(s.substring(e,e+i.length)!==i)return;e+=i.length,a=!1,i="",t++}else if(a)i+=d,t++;else if("%"===d&&t+1<r.length){var u=r[t+1],c=n[u];if(c){var l=s.substring(e).match(c.regex);if(!l||0!==l.index)return;var l=l[0],h=c.extract(l);switch(u){case"Y":case"y":o.year=h;break;case"m":o.month=h;break;case"d":o.day=h;break;case"H":o.hour=h;break;case"M":o.minute=h;break;case"S":o.second=h;break;case"f":o.millisecond=h}e+=l.length}else e++;t+=2}else{if(d!==s[e])return;e++,t++}}if(!(o.month<1||12<o.month||o.day<1||31<o.day||o.hour<0||23<o.hour||o.minute<0||59<o.minute||o.second<0||59<o.second||o.millisecond<0||999<o.millisecond))try{var m=new Date(o.year,o.month-1,o.day,o.hour,o.minute,o.second,o.millisecond);if(!isNaN(m.getTime()))return new f(m)}catch(e){}}}}static getTokenLength(e){return{Y:4,y:2,m:2,d:2,H:2,M:2,S:2,f:3,z:5}[e]||1}parseTimezoneOffset(e){var t={UTC:0,EST:-300,EDT:-240,CST:-360,CDT:-300,PST:-480,PDT:-420};return void 0!==t[e.toUpperCase()]?t[e.toUpperCase()]:(t=e.match(/^([+-])(\d{1,2}):?(\d{2})?$/))?("+"===t[1]?1:-1)*(60*parseInt(t[2],10)+(t[3]?parseInt(t[3],10):0)):this._date?-this._date.getTimezoneOffset():0}static get FORMATS(){return Object.assign({},f.PREDEFINED_FORMATS)}static exposeToGlobal(){"undefined"!=typeof window&&(window.Timez=f)}}f.FORMAT_TOKENS={"%Y":e=>null==(e=e.year())?void 0:e.toString().padStart(4,"0"),"%y":e=>null==(e=e.year())?void 0:e.toString().slice(-2).padStart(2,"0"),"%m":e=>null==(e=e.month())?void 0:e.toString().padStart(2,"0"),"%d":e=>null==(e=e.date())?void 0:e.toString().padStart(2,"0"),"%H":e=>null==(e=e.hour())?void 0:e.toString().padStart(2,"0"),"%M":e=>null==(e=e.minute())?void 0:e.toString().padStart(2,"0"),"%S":e=>null==(e=e.second())?void 0:e.toString().padStart(2,"0"),"%f":e=>null==(e=e.millisecond())?void 0:e.toString().padStart(3,"0"),"%z":e=>{e=e.utcOffset();if(e)return(0<=e?"+":"-")+Math.floor(Math.abs(e)/60).toString().padStart(2,"0")+(Math.abs(e)%60).toString().padStart(2,"0")},"%s":e=>{e=e.valueOf();return e?Math.floor(e/1e3).toString():void 0}},f.PREDEFINED_FORMATS={ISO:"%Y-%m-%dT%H:%M:%S.%fZ",ISO_DATE:"%Y-%m-%d",ISO_TIME:"%H:%M:%S.%fZ",COMPACT:"%Y%m%d%H%M%S",SLASH_DATETIME:"%Y/%m/%d %H:%M:%S.%fZ",SLASH_DATETIME_SEC:"%Y/%m/%d %H:%M:%S",SLASH_DATETIME_MIN:"%Y/%m/%d %H:%M",EUROPEAN:"%d/%m/%Y %H:%M:%S GMT%z",SLASH_DATE:"%Y/%m/%d",TIME_MICRO:"%H:%M:%S.%fZ",TIME_SEC:"%H:%M:%S",CUSTOM_GREETING:"[Bonjour celestin, ][la date actuelle est:: le] %d/%m/%Y [à] %H:%M:%S.%f[Z]"},"undefined"!=typeof window&&(window.Timez=f),timez.Timez=f,timez.default=f}return timez}function requireCooks(){if(!hasRequiredCooks){hasRequiredCooks=1,Object.defineProperty(cooks,"__esModule",{value:!0});var r=requireTimez(),e=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];[...e,...e.map(e=>e.toUpperCase())];class t{static set(e,t,a={}){if(this.isBrowser())try{var i=this.serialize(t),r=encodeURIComponent(i),s=this.buildCookieString(e,r,a);document.cookie=s}catch(e){}}static get(e){if(!this.isBrowser())return null;try{var t,a=this.getAllCookies()[e];return a?(t=decodeURIComponent(a),this.deserialize(t)):null}catch(e){return null}}static remove(e,t="/",a){this.isBrowser()&&(t={expires:new Date(0),path:t,domain:a},this.set(e,"",t))}static has(e){return null!==this.get(e)}static keys(){var e;return this.isBrowser()?(e=this.getAllCookies(),Object.keys(e)):[]}static clear(){var e;this.isBrowser()&&(e=this.getAllCookies(),Object.keys(e).forEach(e=>{this.remove(e)}))}static serialize(e){return e instanceof Date?JSON.stringify({__type:"Date",__value:e.toISOString()}):JSON.stringify(e)}static deserialize(e){e=JSON.parse(e);return e&&"object"==typeof e&&"Date"===e.__type?new Date(e.__value):e}static buildCookieString(e,t,a){a=Object.assign(Object.assign({},this.DEFAULT_OPTIONS),a);let i=e+"="+t;if(void 0!==a.expires){let e;e="number"==typeof a.expires?(new r.Timez).add(a.expires,"seconds").toDate()||new Date:a.expires,i+="; expires="+e.toUTCString()}return a.path&&(i+="; path="+a.path),a.domain&&(i+="; domain="+a.domain),a.secure&&(i+="; secure"),a.sameSite&&(i+="; samesite="+a.sameSite),i}static getAllCookies(){return document.cookie.split(";").reduce((e,t)=>{var[t,a]=t.split("=").map(e=>e.trim());return t&&(e[t]=a||""),e},{})}static isBrowser(){return"undefined"!=typeof window&&"undefined"!=typeof document}static exposeToGlobal(){"undefined"!=typeof window&&(window.Cooks=t)}}t.DEFAULT_OPTIONS={path:"/",secure:!0,sameSite:"lax"},"undefined"!=typeof window&&(window.Cooks=t),cooks.Cooks=t,cooks.default=t}return cooks}var _a,cooksExports=requireCooks();let DEFAULT_LOCALE="en",SUPPORTED_LOCALES=["en","fr"],COOKIE_NAME="app_locale",getSavedLocale=(e=SUPPORTED_LOCALES)=>{var t=cooksExports.Cooks.get(COOKIE_NAME);return("object"==typeof e&&Array.isArray(e)&&0<e.length?e:SUPPORTED_LOCALES).includes(t)?t:DEFAULT_LOCALE},saveLocale=e=>{cooksExports.Cooks.set(COOKIE_NAME,e,{expires:31536e3,sameSite:"strict"})},PATH_CONFIG={SRC_DIR:"/src"},SRC_DIR=(null==(_a=null==process?void 0:process.env)?void 0:_a.VITE_APP_SRC_DIR)||"/src";export{COOKIE_NAME,DEFAULT_LOCALE,PATH_CONFIG,SRC_DIR,SUPPORTED_LOCALES,getSavedLocale,saveLocale};
1
+ let DEFAULT_CONFIG="base",configManagerConfig=null,setConfigManagerConfig=n=>{configManagerConfig=n};export{DEFAULT_CONFIG,configManagerConfig,setConfigManagerConfig};
2
2
  //# sourceMappingURL=config.min.js.map
@@ -0,0 +1,19 @@
1
+ interface ConfigOptions {
2
+ moduleName?: string;
3
+ defaultValue?: any;
4
+ pathSeparator?: string;
5
+ }
6
+
7
+ declare class ConfigService {
8
+ private resources;
9
+ private loadedModules;
10
+ constructor();
11
+ initialize(): Promise<void>;
12
+ loadAllConfigs(): Promise<void>;
13
+ loadModule(moduleName: string): Promise<void>;
14
+ get(key: string, options?: ConfigOptions): any;
15
+ getConfig(moduleName?: string): Record<string, any>;
16
+ reload(): Promise<void>;
17
+ }
18
+
19
+ export { ConfigService };
@@ -0,0 +1,151 @@
1
+
2
+
3
+
4
+
5
+ function __awaiter(thisArg, _arguments, P, generator) {
6
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
7
+ return new (P || (P = Promise))(function (resolve, reject) {
8
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
9
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
10
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
11
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
12
+ });
13
+ }
14
+
15
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
16
+ var e = new Error(message);
17
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
18
+ };
19
+
20
+ const mergeDeep = (target, source) => {
21
+ if (typeof target !== 'object' || typeof source !== 'object')
22
+ return source;
23
+ const output = Object.assign({}, target);
24
+ for (const key in source) {
25
+ if (source.hasOwnProperty(key)) {
26
+ if (target.hasOwnProperty(key)) {
27
+ output[key] = mergeDeep(target[key], source[key]);
28
+ }
29
+ else {
30
+ output[key] = source[key];
31
+ }
32
+ }
33
+ }
34
+ return output;
35
+ };
36
+
37
+ let configManagerConfig = null;
38
+
39
+ const loadBaseConfig = () => __awaiter(void 0, void 0, void 0, function* () {
40
+ try {
41
+ if (!(configManagerConfig === null || configManagerConfig === void 0 ? void 0 : configManagerConfig.base)) {
42
+ console.warn('No base config found');
43
+ return {};
44
+ }
45
+ const baseConfigs = yield Promise.all(Object.entries(configManagerConfig.base).map((_a) => __awaiter(void 0, [_a], void 0, function* ([key, loader]) {
46
+ try {
47
+ const config = yield loader();
48
+ return { key, config };
49
+ }
50
+ catch (error) {
51
+ console.error(`Failed to load base config ${key}:`, error);
52
+ return { key, config: {} };
53
+ }
54
+ })));
55
+ return baseConfigs.reduce((acc, { key, config }) => {
56
+ return Object.assign(Object.assign({}, acc), config);
57
+ }, {});
58
+ }
59
+ catch (error) {
60
+ console.error('Failed to load base config:', error);
61
+ return {};
62
+ }
63
+ });
64
+ const loadModulesConfigs = () => __awaiter(void 0, void 0, void 0, function* () {
65
+ const results = [];
66
+ {
67
+ return results;
68
+ }
69
+ });
70
+ const loadModuleConfig = (moduleName) => __awaiter(void 0, void 0, void 0, function* () {
71
+ var _a;
72
+ if (!((_a = void 0 ) === null || _a === void 0 ? void 0 : _a[moduleName])) {
73
+ return undefined;
74
+ }
75
+ try {
76
+ const loader = configManagerConfig.modules[moduleName];
77
+ const config = yield loader();
78
+ return {
79
+ moduleName,
80
+ config
81
+ };
82
+ }
83
+ catch (error) {
84
+ console.error(`Failed to load config for module "${moduleName}"`, error);
85
+ return undefined;
86
+ }
87
+ });
88
+
89
+ class ConfigService {
90
+ constructor() {
91
+ Object.defineProperty(this, "resources", {
92
+ enumerable: true,
93
+ configurable: true,
94
+ writable: true,
95
+ value: {}
96
+ });
97
+ Object.defineProperty(this, "loadedModules", {
98
+ enumerable: true,
99
+ configurable: true,
100
+ writable: true,
101
+ value: new Set()
102
+ });
103
+ }
104
+ initialize() {
105
+ return __awaiter(this, void 0, void 0, function* () {
106
+ yield this.loadAllConfigs();
107
+ });
108
+ }
109
+ loadAllConfigs() {
110
+ return __awaiter(this, void 0, void 0, function* () {
111
+ const base = yield loadBaseConfig();
112
+ const modules = yield loadModulesConfigs();
113
+ this.resources = modules.reduce((acc, { moduleName, config }) => {
114
+ return mergeDeep(acc, { [moduleName]: config });
115
+ }, { base });
116
+ modules.forEach(({ moduleName }) => {
117
+ this.loadedModules.add(moduleName);
118
+ });
119
+ });
120
+ }
121
+ loadModule(moduleName) {
122
+ return __awaiter(this, void 0, void 0, function* () {
123
+ if (this.loadedModules.has(moduleName))
124
+ return;
125
+ const moduleData = yield loadModuleConfig(moduleName);
126
+ if (moduleData === null || moduleData === void 0 ? void 0 : moduleData.config) {
127
+ this.resources[moduleName] = mergeDeep(this.resources[moduleName] || {}, moduleData.config);
128
+ this.loadedModules.add(moduleName);
129
+ }
130
+ });
131
+ }
132
+ get(key, options = {}) {
133
+ const { moduleName = 'base', defaultValue = undefined, pathSeparator = '.' } = options;
134
+ const resource = this.resources[moduleName];
135
+ if (!resource) {
136
+ return defaultValue;
137
+ }
138
+ const result = key.split(pathSeparator).reduce((acc, part) => {
139
+ return acc && acc[part] !== undefined ? acc[part] : undefined;
140
+ }, resource);
141
+ return result !== undefined ? result : defaultValue;
142
+ }
143
+ getConfig(moduleName = 'base') {
144
+ return this.resources[moduleName] || {};
145
+ }
146
+ reload() {
147
+ return this.loadAllConfigs();
148
+ }
149
+ }
150
+
151
+ export { ConfigService };
@@ -0,0 +1,2 @@
1
+ function __awaiter(e,a,d,l){return new(d=d||Promise)(function(i,o){function n(e){try{t(l.next(e))}catch(e){o(e)}}function r(e){try{t(l.throw(e))}catch(e){o(e)}}function t(e){var o;e.done?i(e.value):((o=e.value)instanceof d?o:new d(function(e){e(o)})).then(n,r)}t((l=l.apply(e,a||[])).next())})}let mergeDeep=(e,o)=>{if("object"!=typeof e||"object"!=typeof o)return o;var i,n=Object.assign({},e);for(i in o)o.hasOwnProperty(i)&&(e.hasOwnProperty(i)?n[i]=mergeDeep(e[i],o[i]):n[i]=o[i]);return n},configManagerConfig=null,loadBaseConfig=()=>__awaiter(void 0,void 0,void 0,function*(){try{return null!=configManagerConfig&&configManagerConfig.base?(yield Promise.all(Object.entries(configManagerConfig.base).map(e=>__awaiter(void 0,[e],void 0,function*([o,e]){try{return{key:o,config:yield e()}}catch(e){return{key:o,config:{}}}})))).reduce((e,{config:o})=>Object.assign(Object.assign({},e),o),{}):{}}catch(e){return{}}}),loadModulesConfigs=()=>__awaiter(void 0,void 0,void 0,function*(){return[]}),loadModuleConfig=e=>__awaiter(void 0,void 0,void 0,function*(){});class ConfigService{constructor(){Object.defineProperty(this,"resources",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"loadedModules",{enumerable:!0,configurable:!0,writable:!0,value:new Set})}initialize(){return __awaiter(this,void 0,void 0,function*(){yield this.loadAllConfigs()})}loadAllConfigs(){return __awaiter(this,void 0,void 0,function*(){var e=yield loadBaseConfig(),o=yield loadModulesConfigs();this.resources=o.reduce((e,{moduleName:o,config:i})=>mergeDeep(e,{[o]:i}),{base:e}),o.forEach(({moduleName:e})=>{this.loadedModules.add(e)})})}loadModule(o){return __awaiter(this,void 0,void 0,function*(){var e;this.loadedModules.has(o)||null!=(e=yield loadModuleConfig(o))&&e.config&&(this.resources[o]=mergeDeep(this.resources[o]||{},e.config),this.loadedModules.add(o))})}get(e,o={}){var{moduleName:o="base",defaultValue:i=void 0,pathSeparator:n="."}=o,o=this.resources[o];return o&&void 0!==(e=e.split(n).reduce((e,o)=>e&&void 0!==e[o]?e[o]:void 0,o))?e:i}getConfig(e="base"){return this.resources[e]||{}}reload(){return this.loadAllConfigs()}}export{ConfigService};
2
+ //# sourceMappingURL=ConfigService.min.js.map
@@ -0,0 +1,33 @@
1
+ import React from "react";
2
+ import { useEffect, useState, useCallback } from 'react';
3
+ import { useConfigManager } from '../providers/ConfigProvider';
4
+ export const useConfig = moduleName => {
5
+ const configManager = useConfigManager();
6
+ const [isModuleLoading, setIsModuleLoading] = useState(false);
7
+ const [moduleLoaded, setModuleLoaded] = useState(!moduleName);
8
+ const cf = useCallback((key, options) => {
9
+ const finalOptions = {
10
+ ...options,
11
+ moduleName: options?.moduleName || moduleName || 'base'
12
+ };
13
+ return configManager.get(key, finalOptions);
14
+ }, [configManager, moduleName]);
15
+ useEffect(() => {
16
+ if (moduleName && !moduleLoaded) {
17
+ setIsModuleLoading(true);
18
+ configManager.loadModuleConfig(moduleName).then(() => {
19
+ setModuleLoaded(true);
20
+ }).finally(() => {
21
+ setIsModuleLoading(false);
22
+ });
23
+ }
24
+ }, [moduleName, moduleLoaded, configManager]);
25
+ return {
26
+ cf,
27
+ getConfig: configManager.getConfig,
28
+ reloadConfig: configManager.reloadConfig,
29
+ isLoading: configManager.isLoading || isModuleLoading,
30
+ isModuleLoaded: moduleLoaded,
31
+ loadModuleConfig: configManager.loadModuleConfig
32
+ };
33
+ };
@@ -0,0 +1,39 @@
1
+ import { useEffect, useState, useCallback } from 'react';
2
+ import { useConfigManager } from '../providers/ConfigProvider';
3
+
4
+ export const useConfig = (moduleName?: string) => {
5
+ const configManager = useConfigManager();
6
+ const [isModuleLoading, setIsModuleLoading] = useState(false);
7
+ const [moduleLoaded, setModuleLoaded] = useState(!moduleName);
8
+
9
+ const cf = useCallback((key: string, options?: any) => {
10
+ const finalOptions = {
11
+ ...options,
12
+ moduleName: options?.moduleName || moduleName || 'base'
13
+ };
14
+
15
+ return configManager.get(key, finalOptions);
16
+ }, [configManager, moduleName]);
17
+
18
+ useEffect(() => {
19
+ if (moduleName && !moduleLoaded) {
20
+ setIsModuleLoading(true);
21
+ configManager.loadModuleConfig(moduleName)
22
+ .then(() => {
23
+ setModuleLoaded(true);
24
+ })
25
+ .finally(() => {
26
+ setIsModuleLoading(false);
27
+ });
28
+ }
29
+ }, [moduleName, moduleLoaded, configManager]);
30
+
31
+ return {
32
+ cf,
33
+ getConfig: configManager.getConfig,
34
+ reloadConfig: configManager.reloadConfig,
35
+ isLoading: configManager.isLoading || isModuleLoading,
36
+ isModuleLoaded: moduleLoaded,
37
+ loadModuleConfig: configManager.loadModuleConfig,
38
+ };
39
+ };
package/index.d.ts CHANGED
@@ -1,34 +1,41 @@
1
- type ConfigValue = string | number | boolean | null | ConfigValue[] | {
2
- [key: string]: ConfigValue;
3
- };
4
- type ConfigPath = string | string[];
5
- interface ConfigOptions {
6
- moduleName?: string;
7
- defaultValue?: ConfigValue;
8
- required?: boolean;
1
+ interface ConfigMap {
2
+ [key: string]: () => Promise<Record<string, any>>;
9
3
  }
10
- interface Configuration {
11
- get: <T = ConfigValue>(path: ConfigPath, options?: ConfigOptions) => T | undefined;
12
- getOrThrow: <T = ConfigValue>(path: ConfigPath, moduleName?: string) => T;
13
- getAll: (moduleName?: string) => Record<string, any>;
14
- has: (path: ConfigPath, moduleName?: string) => boolean;
15
- set: (path: ConfigPath, value: ConfigValue, moduleName?: string) => void;
16
- merge: (config: Record<string, any>, moduleName?: string) => void;
17
- getEnv: (key: string, defaultValue?: string) => string | undefined;
18
- isProduction: () => boolean;
19
- isDevelopment: () => boolean;
20
- isTest: () => boolean;
4
+ interface ModuleConfigs {
5
+ [moduleName: string]: () => Promise<Record<string, any>>;
21
6
  }
22
- interface ConfigContextValue extends Configuration {
23
- loadModuleConfig: (moduleName: string) => Promise<void>;
24
- isLoading: boolean;
7
+ interface ConfigData {
8
+ base: ConfigMap;
9
+ modules?: ModuleConfigs;
25
10
  }
11
+ type ConfigManagerConfig = ConfigData;
26
12
 
27
- declare const ConfigProvider: React.FC<{
13
+ declare const ConfigManagerProvider: React.FC<{
28
14
  children: React.ReactNode;
29
- preloadModules?: string[];
15
+ configs: ConfigManagerConfig;
30
16
  }>;
31
- declare const useConfig: () => ConfigContextValue;
17
+ declare const useConfigManager: () => {
18
+ get: (key: string, options?: any) => any;
19
+ getConfig: (moduleName?: string) => Record<string, any>;
20
+ reloadConfig: () => Promise<void>;
21
+ isLoading: boolean;
22
+ loadModuleConfig: (moduleName: string) => Promise<void>;
23
+ };
24
+
25
+ declare const useConfig: (moduleName?: string) => {
26
+ cf: (key: string, options?: any) => any;
27
+ getConfig: (moduleName?: string) => Record<string, any>;
28
+ reloadConfig: () => Promise<void>;
29
+ isLoading: boolean;
30
+ isModuleLoaded: boolean;
31
+ loadModuleConfig: (moduleName: string) => Promise<void>;
32
+ };
33
+
34
+ interface ConfigOptions {
35
+ moduleName?: string;
36
+ defaultValue?: any;
37
+ pathSeparator?: string;
38
+ }
32
39
 
33
- export { ConfigProvider, useConfig };
34
- export type { ConfigContextValue, ConfigOptions, ConfigPath, ConfigValue, Configuration };
40
+ export { ConfigManagerProvider, useConfig, useConfigManager };
41
+ export type { ConfigManagerConfig, ConfigOptions };