@rxap/config 21.0.1 → 22.0.0-dev.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.
Files changed (136) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/compodoc/changelog.html +5 -0
  3. package/compodoc/dependencies.html +4 -4
  4. package/compodoc/js/search/search_index.js +2 -2
  5. package/compodoc/properties.html +1 -1
  6. package/docs/documentation.json +180 -180
  7. package/docs/html/classes/ConfigLoaderService.html +2 -2
  8. package/docs/html/classes/ConfigService.html +7 -7
  9. package/docs/html/classes/ConfigTestingService.html +2 -2
  10. package/docs/html/enums/ConfigLoadMethod.html +2 -2
  11. package/docs/html/enums/ConfigLoadingStrategy.html +2 -2
  12. package/docs/html/functions/ProvideConfig.html +1 -1
  13. package/docs/html/functions/defaultConfigLoadErrorHandler.html +2 -2
  14. package/docs/html/functions/dnsLookup.html +1 -1
  15. package/docs/html/functions/dnsResolver.html +1 -1
  16. package/docs/html/functions/fetchCidContent.html +1 -1
  17. package/docs/html/functions/fetchCidContentAsJson.html +1 -1
  18. package/docs/html/functions/fetchCidContentViaHttp.html +1 -1
  19. package/docs/html/functions/fetchContentViaHttp.html +1 -1
  20. package/docs/html/functions/localPathIpfsGateway.html +1 -1
  21. package/docs/html/functions/localSubDomainIpfsGateway.html +1 -1
  22. package/docs/html/functions/raceSuccess.html +2 -2
  23. package/docs/html/functions/showConfigLoadError.html +2 -2
  24. package/docs/html/functions/storachaIpfsGateway.html +1 -1
  25. package/docs/html/functions/w3sIpfsGateway.html +1 -1
  26. package/docs/html/hierarchy.html +1 -1
  27. package/docs/html/index.html +2 -2
  28. package/docs/html/interfaces/AppsNavigationConfig.html +2 -2
  29. package/docs/html/interfaces/Config.html +2 -2
  30. package/docs/html/interfaces/ConfigLoadError.html +4 -4
  31. package/docs/html/interfaces/ConfigLoadOptions.html +8 -8
  32. package/docs/html/interfaces/LogoConfig.html +2 -2
  33. package/docs/html/interfaces/NavigationConfig.html +2 -2
  34. package/docs/html/interfaces/Oauth2Config.html +2 -2
  35. package/docs/html/interfaces/i18nConfig.html +2 -2
  36. package/docs/html/modules.html +1 -1
  37. package/docs/html/types/AnySchema.html +1 -1
  38. package/docs/html/types/ConfigLoadErrorHandler.html +2 -2
  39. package/docs/html/types/ConfigLoadErrorKind.html +2 -2
  40. package/docs/html/types/ConfigRequestOptions.html +1 -1
  41. package/docs/html/types/IpfsGatewayFunction.html +1 -1
  42. package/docs/html/types/Join.html +1 -1
  43. package/docs/html/types/LanguagesConfig.html +1 -1
  44. package/docs/html/types/Leaves.html +1 -1
  45. package/docs/html/types/NoInferType.html +1 -1
  46. package/docs/html/types/Paths.html +1 -1
  47. package/docs/html/variables/RXAP_CONFIG.html +1 -1
  48. package/docs/html/variables/defaultDnsServers.html +1 -1
  49. package/docs/html/variables/defaultIpfsGatewayServers.html +1 -1
  50. package/docs/markdown/README.md +1 -1
  51. package/docs/markdown/classes/ConfigLoaderService.md +6 -6
  52. package/docs/markdown/classes/ConfigService.md +23 -23
  53. package/docs/markdown/classes/ConfigTestingService.md +8 -8
  54. package/docs/markdown/enumerations/ConfigLoadMethod.md +6 -6
  55. package/docs/markdown/enumerations/ConfigLoadingStrategy.md +4 -4
  56. package/docs/markdown/functions/ProvideConfig.md +2 -2
  57. package/docs/markdown/functions/defaultConfigLoadErrorHandler.md +2 -2
  58. package/docs/markdown/functions/dnsLookup.md +2 -2
  59. package/docs/markdown/functions/dnsResolver.md +2 -2
  60. package/docs/markdown/functions/fetchCidContent.md +2 -2
  61. package/docs/markdown/functions/fetchCidContentAsJson.md +2 -2
  62. package/docs/markdown/functions/fetchCidContentViaHttp.md +2 -2
  63. package/docs/markdown/functions/fetchContentViaHttp.md +2 -2
  64. package/docs/markdown/functions/localPathIpfsGateway.md +2 -2
  65. package/docs/markdown/functions/localSubDomainIpfsGateway.md +2 -2
  66. package/docs/markdown/functions/raceSuccess.md +2 -2
  67. package/docs/markdown/functions/showConfigLoadError.md +2 -2
  68. package/docs/markdown/functions/storachaIpfsGateway.md +2 -2
  69. package/docs/markdown/functions/w3sIpfsGateway.md +2 -2
  70. package/docs/markdown/globals.md +2 -2
  71. package/docs/markdown/interfaces/AppsNavigationConfig.md +12 -12
  72. package/docs/markdown/interfaces/Config.md +6 -6
  73. package/docs/markdown/interfaces/ConfigLoadError.md +9 -9
  74. package/docs/markdown/interfaces/ConfigLoadOptions.md +17 -17
  75. package/docs/markdown/interfaces/LogoConfig.md +5 -5
  76. package/docs/markdown/interfaces/NavigationConfig.md +9 -9
  77. package/docs/markdown/interfaces/Oauth2Config.md +3 -3
  78. package/docs/markdown/interfaces/i18nConfig.md +4 -4
  79. package/docs/markdown/type-aliases/AnySchema.md +2 -2
  80. package/docs/markdown/type-aliases/ConfigLoadErrorHandler.md +2 -2
  81. package/docs/markdown/type-aliases/ConfigLoadErrorKind.md +2 -2
  82. package/docs/markdown/type-aliases/ConfigRequestOptions.md +2 -2
  83. package/docs/markdown/type-aliases/IpfsGatewayFunction.md +2 -2
  84. package/docs/markdown/type-aliases/Join.md +2 -2
  85. package/docs/markdown/type-aliases/LanguagesConfig.md +2 -2
  86. package/docs/markdown/type-aliases/Leaves.md +2 -2
  87. package/docs/markdown/type-aliases/NoInferType.md +2 -2
  88. package/docs/markdown/type-aliases/Paths.md +2 -2
  89. package/docs/markdown/variables/RXAP_CONFIG.md +2 -2
  90. package/docs/markdown/variables/defaultDnsServers.md +2 -2
  91. package/docs/markdown/variables/defaultIpfsGatewayServers.md +2 -2
  92. package/docs/wiki/Class.ConfigLoaderService.md +5 -5
  93. package/docs/wiki/Class.ConfigService.md +22 -22
  94. package/docs/wiki/Class.ConfigTestingService.md +7 -7
  95. package/docs/wiki/Enumeration.ConfigLoadMethod.md +5 -5
  96. package/docs/wiki/Enumeration.ConfigLoadingStrategy.md +3 -3
  97. package/docs/wiki/Function.ProvideConfig.md +1 -1
  98. package/docs/wiki/Function.defaultConfigLoadErrorHandler.md +1 -1
  99. package/docs/wiki/Function.dnsLookup.md +1 -1
  100. package/docs/wiki/Function.dnsResolver.md +1 -1
  101. package/docs/wiki/Function.fetchCidContent.md +1 -1
  102. package/docs/wiki/Function.fetchCidContentAsJson.md +1 -1
  103. package/docs/wiki/Function.fetchCidContentViaHttp.md +1 -1
  104. package/docs/wiki/Function.fetchContentViaHttp.md +1 -1
  105. package/docs/wiki/Function.localPathIpfsGateway.md +1 -1
  106. package/docs/wiki/Function.localSubDomainIpfsGateway.md +1 -1
  107. package/docs/wiki/Function.raceSuccess.md +1 -1
  108. package/docs/wiki/Function.showConfigLoadError.md +1 -1
  109. package/docs/wiki/Function.storachaIpfsGateway.md +1 -1
  110. package/docs/wiki/Function.w3sIpfsGateway.md +1 -1
  111. package/docs/wiki/Interface.AppsNavigationConfig.md +11 -11
  112. package/docs/wiki/Interface.Config.md +5 -5
  113. package/docs/wiki/Interface.ConfigLoadError.md +8 -8
  114. package/docs/wiki/Interface.ConfigLoadOptions.md +16 -16
  115. package/docs/wiki/Interface.LogoConfig.md +4 -4
  116. package/docs/wiki/Interface.NavigationConfig.md +8 -8
  117. package/docs/wiki/Interface.Oauth2Config.md +2 -2
  118. package/docs/wiki/Interface.i18nConfig.md +3 -3
  119. package/docs/wiki/TypeAlias.AnySchema.md +1 -1
  120. package/docs/wiki/TypeAlias.ConfigLoadErrorHandler.md +1 -1
  121. package/docs/wiki/TypeAlias.ConfigLoadErrorKind.md +1 -1
  122. package/docs/wiki/TypeAlias.ConfigRequestOptions.md +1 -1
  123. package/docs/wiki/TypeAlias.IpfsGatewayFunction.md +1 -1
  124. package/docs/wiki/TypeAlias.Join.md +1 -1
  125. package/docs/wiki/TypeAlias.LanguagesConfig.md +1 -1
  126. package/docs/wiki/TypeAlias.Leaves.md +1 -1
  127. package/docs/wiki/TypeAlias.NoInferType.md +1 -1
  128. package/docs/wiki/TypeAlias.Paths.md +1 -1
  129. package/docs/wiki/Variable.RXAP_CONFIG.md +1 -1
  130. package/docs/wiki/Variable.defaultDnsServers.md +1 -1
  131. package/docs/wiki/Variable.defaultIpfsGatewayServers.md +1 -1
  132. package/docs/wiki/globals.md +1 -1
  133. package/fesm2022/rxap-config.mjs +581 -713
  134. package/fesm2022/rxap-config.mjs.map +1 -1
  135. package/package.json +8 -8
  136. package/types/rxap-config.d.ts +223 -257
@@ -1,740 +1,608 @@
1
- import * as i0 from '@angular/core';
2
- import { inject, Injectable, InjectionToken, Optional, Inject } from '@angular/core';
3
- import { firstValueFrom, Observable, catchError, EMPTY, race, ReplaySubject } from 'rxjs';
4
- import { HttpClient } from '@angular/common/http';
5
- import { tap, finalize, share } from 'rxjs/operators';
6
- import { SetToObject, getFromObject, JoinPath, deepMerge, coerceArray, CoercePrefix, SetObjectValue } from '@rxap/utilities';
7
- import { log } from '@rxap/rxjs';
8
-
9
- /**
10
- * The default config load error handler. Shows the error message in an overlay and reloads the
11
- * page after 30 s for required config urls. Logs a warning for optional config urls.
12
- *
13
- * Can be used as fallback in a custom error handler for error kinds it does not handle.
14
- */
1
+ import * as i0 from "@angular/core";
2
+ import { Inject, Injectable, InjectionToken, Optional, inject } from "@angular/core";
3
+ import { EMPTY, Observable, ReplaySubject, catchError, firstValueFrom, race } from "rxjs";
4
+ import { HttpClient } from "@angular/common/http";
5
+ import { finalize, share, tap } from "rxjs/operators";
6
+ import { CoercePrefix, JoinPath, SetObjectValue, SetToObject, coerceArray, deepMerge, getFromObject } from "@rxap/utilities";
7
+ import { log } from "@rxap/rxjs";
15
8
  function defaultConfigLoadErrorHandler(error) {
16
- if (error.required) {
17
- showConfigLoadError(error.message);
18
- }
19
- else {
20
- console.warn(error.message);
21
- }
9
+ if (error.required) showConfigLoadError(error.message);
10
+ else console.warn(error.message);
22
11
  }
23
- /**
24
- * Appends the message to the config error overlay and schedules a page reload in 30 s.
25
- */
26
12
  function showConfigLoadError(message) {
27
- const hasUl = document.getElementById('rxap-config-error') !== null;
28
- const ul = document.getElementById('rxap-config-error') ?? document.createElement('ul');
29
- ul.id = 'rxap-config-error';
30
- ul.style.position = 'fixed';
31
- ul.style.bottom = '16px';
32
- ul.style.right = '16px';
33
- ul.style.backgroundColor = 'white';
34
- ul.style.padding = '32px';
35
- ul.style.zIndex = '99999999';
36
- ul.style.color = 'black';
37
- const messageLi = document.createElement('li');
38
- messageLi.innerText = message;
39
- ul.appendChild(messageLi);
40
- const refreshHintLi = document.createElement('li');
41
- refreshHintLi.innerText = 'Please refresh the page to try again.';
42
- ul.appendChild(refreshHintLi);
43
- const autoRefreshHintLi = document.createElement('li');
44
- autoRefreshHintLi.innerText = 'The page will refresh automatically in 30 seconds.';
45
- ul.appendChild(autoRefreshHintLi);
46
- if (!hasUl) {
47
- document.body.appendChild(ul);
48
- }
49
- setTimeout(() => location.reload(), 30000);
50
- }
51
-
52
- class ConfigLoaderService {
53
- constructor() {
54
- this.http = inject(HttpClient);
55
- this.configs = new Map();
56
- this.configLoading = new Map();
57
- }
58
- async load$(url) {
59
- if (this.configs.has(url)) {
60
- return this.configs.get(url);
61
- }
62
- if (this.configLoading.has(url)) {
63
- return firstValueFrom(this.configLoading.get(url));
64
- }
65
- const loading$ = this.http.get(url).pipe(tap(config => this.configs.set(url, config)), finalize(() => this.configLoading.delete(url)), share());
66
- this.configLoading.set(url, loading$);
67
- return firstValueFrom(loading$);
68
- }
69
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.9", ngImport: i0, type: ConfigLoaderService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
70
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.9", ngImport: i0, type: ConfigLoaderService, providedIn: 'root' }); }
71
- }
72
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.9", ngImport: i0, type: ConfigLoaderService, decorators: [{
73
- type: Injectable,
74
- args: [{ providedIn: 'root' }]
75
- }] });
76
-
77
- class ConfigTestingService {
78
- constructor() {
79
- this.config = {};
80
- }
81
- // eslint-disable-next-line @typescript-eslint/no-empty-function
82
- clearLocalConfig() {
83
- }
84
- set(propertyPath, value) {
85
- SetToObject(this.config, propertyPath, value);
86
- }
87
- get(propertyPath, defaultValue) {
88
- return getFromObject(this.config, propertyPath, defaultValue);
89
- }
90
- getOrThrow(propertyPath) {
91
- const value = this.get(propertyPath);
92
- if (value === undefined) {
93
- throw new Error(`Could not find config in path '${propertyPath}'`);
94
- }
95
- return value;
96
- }
97
- // eslint-disable-next-line @typescript-eslint/no-empty-function
98
- setLocalConfig(config) {
99
- }
100
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.9", ngImport: i0, type: ConfigTestingService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
101
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.9", ngImport: i0, type: ConfigTestingService }); }
13
+ const hasUl = document.getElementById("rxap-config-error") !== null;
14
+ const ul = document.getElementById("rxap-config-error") ?? document.createElement("ul");
15
+ ul.id = "rxap-config-error";
16
+ ul.style.position = "fixed";
17
+ ul.style.bottom = "16px";
18
+ ul.style.right = "16px";
19
+ ul.style.backgroundColor = "white";
20
+ ul.style.padding = "32px";
21
+ ul.style.zIndex = "99999999";
22
+ ul.style.color = "black";
23
+ const messageLi = document.createElement("li");
24
+ messageLi.innerText = message;
25
+ ul.appendChild(messageLi);
26
+ const refreshHintLi = document.createElement("li");
27
+ refreshHintLi.innerText = "Please refresh the page to try again.";
28
+ ul.appendChild(refreshHintLi);
29
+ const autoRefreshHintLi = document.createElement("li");
30
+ autoRefreshHintLi.innerText = "The page will refresh automatically in 30 seconds.";
31
+ ul.appendChild(autoRefreshHintLi);
32
+ if (!hasUl) document.body.appendChild(ul);
33
+ setTimeout(() => location.reload(), 3e4);
102
34
  }
103
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.9", ngImport: i0, type: ConfigTestingService, decorators: [{
104
- type: Injectable
105
- }] });
106
-
107
- const RXAP_CONFIG = new InjectionToken('rxap/config');
108
-
109
- // TODO : move to separate package
110
- /**
111
- * Similar to Promise.race() but only resolves with the first successful promise.
112
- * It will only reject if all promises reject.
113
- */
35
+ var ConfigLoaderService = class ConfigLoaderService {
36
+ constructor() {
37
+ this.http = inject(HttpClient);
38
+ this.configs = /* @__PURE__ */ new Map();
39
+ this.configLoading = /* @__PURE__ */ new Map();
40
+ }
41
+ async load$(url) {
42
+ if (this.configs.has(url)) return this.configs.get(url);
43
+ if (this.configLoading.has(url)) return firstValueFrom(this.configLoading.get(url));
44
+ const loading$ = this.http.get(url).pipe(tap((config) => this.configs.set(url, config)), finalize(() => this.configLoading.delete(url)), share());
45
+ this.configLoading.set(url, loading$);
46
+ return firstValueFrom(loading$);
47
+ }
48
+ static {
49
+ this.ɵfac = i0.ɵɵngDeclareFactory({
50
+ minVersion: "12.0.0",
51
+ version: "22.3.0",
52
+ ngImport: i0,
53
+ type: ConfigLoaderService,
54
+ deps: [],
55
+ target: i0.ɵɵFactoryTarget.Injectable
56
+ });
57
+ }
58
+ static {
59
+ this.ɵprov = i0.ɵɵngDeclareInjectable({
60
+ minVersion: "12.0.0",
61
+ version: "22.3.0",
62
+ ngImport: i0,
63
+ type: ConfigLoaderService,
64
+ providedIn: "root"
65
+ });
66
+ }
67
+ };
68
+ i0.ɵɵngDeclareClassMetadata({
69
+ minVersion: "12.0.0",
70
+ version: "22.3.0",
71
+ ngImport: i0,
72
+ type: ConfigLoaderService,
73
+ decorators: [{
74
+ type: Injectable,
75
+ args: [{ providedIn: "root" }]
76
+ }]
77
+ });
78
+ var ConfigTestingService = class ConfigTestingService {
79
+ constructor() {
80
+ this.config = {};
81
+ }
82
+ clearLocalConfig() {}
83
+ set(propertyPath, value) {
84
+ SetToObject(this.config, propertyPath, value);
85
+ }
86
+ get(propertyPath, defaultValue) {
87
+ return getFromObject(this.config, propertyPath, defaultValue);
88
+ }
89
+ getOrThrow(propertyPath) {
90
+ const value = this.get(propertyPath);
91
+ if (value === void 0) throw new Error(`Could not find config in path '${propertyPath}'`);
92
+ return value;
93
+ }
94
+ setLocalConfig(config) {}
95
+ static {
96
+ this.ɵfac = i0.ɵɵngDeclareFactory({
97
+ minVersion: "12.0.0",
98
+ version: "22.3.0",
99
+ ngImport: i0,
100
+ type: ConfigTestingService,
101
+ deps: [],
102
+ target: i0.ɵɵFactoryTarget.Injectable
103
+ });
104
+ }
105
+ static {
106
+ this.ɵprov = i0.ɵɵngDeclareInjectable({
107
+ minVersion: "12.0.0",
108
+ version: "22.3.0",
109
+ ngImport: i0,
110
+ type: ConfigTestingService
111
+ });
112
+ }
113
+ };
114
+ i0.ɵɵngDeclareClassMetadata({
115
+ minVersion: "12.0.0",
116
+ version: "22.3.0",
117
+ ngImport: i0,
118
+ type: ConfigTestingService,
119
+ decorators: [{ type: Injectable }]
120
+ });
121
+ const RXAP_CONFIG = new InjectionToken("rxap/config");
114
122
  async function raceSuccess(promises) {
115
- return new Promise((resolve, reject) => {
116
- let rejectionCount = 0;
117
- promises.forEach((promise) => {
118
- promise.then(
119
- // On success, resolve the entire raceSuccess promise
120
- (value) => resolve(value),
121
- // On rejection, count it and check if all promises rejected
122
- () => {
123
- rejectionCount++;
124
- if (rejectionCount === promises.length) {
125
- reject(new Error('All promises were rejected'));
126
- }
127
- // Otherwise continue waiting for other promises
128
- });
129
- });
130
- });
123
+ return new Promise((resolve, reject) => {
124
+ let rejectionCount = 0;
125
+ promises.forEach((promise) => {
126
+ promise.then((value) => resolve(value), () => {
127
+ rejectionCount++;
128
+ if (rejectionCount === promises.length) reject(/* @__PURE__ */ new Error("All promises were rejected"));
129
+ });
130
+ });
131
+ });
131
132
  }
132
133
  async function dnsResolver(endpoint, name, type) {
133
- const response = await fetch(`${endpoint}?name=${name}&type=${type}`, {
134
- method: 'GET',
135
- headers: {
136
- 'Accept': 'application/dns-json',
137
- 'Cache-Control': 'no-cache, no-store, must-revalidate',
138
- 'Pragma': 'no-cache',
139
- 'Expires': '0',
140
- },
141
- });
142
- if (!response.ok) {
143
- throw new Error(`Failed to resolve DNS via ${endpoint} (${response.status}): ${response.statusText}`);
144
- }
145
- const result = await response.json();
146
- // Basic validation of the response structure
147
- if (!result || !Array.isArray(result.Answer) || result.Answer.length === 0 || !result.Answer[0].data) {
148
- throw new Error(`Invalid DNS response structure from ${endpoint} for ${name} ${type}`);
149
- }
150
- const data = result.Answer[0].data;
151
- // Remove surrounding quotes often found in TXT records
152
- return data.replace(/^"(.*)"$/, '$1');
134
+ const response = await fetch(`${endpoint}?name=${name}&type=${type}`, {
135
+ method: "GET",
136
+ headers: {
137
+ "Accept": "application/dns-json",
138
+ "Cache-Control": "no-cache, no-store, must-revalidate",
139
+ "Pragma": "no-cache",
140
+ "Expires": "0"
141
+ }
142
+ });
143
+ if (!response.ok) throw new Error(`Failed to resolve DNS via ${endpoint} (${response.status}): ${response.statusText}`);
144
+ const result = await response.json();
145
+ if (!result || !Array.isArray(result.Answer) || result.Answer.length === 0 || !result.Answer[0].data) throw new Error(`Invalid DNS response structure from ${endpoint} for ${name} ${type}`);
146
+ return result.Answer[0].data.replace(/^"(.*)"$/, "$1");
153
147
  }
154
- const defaultDnsServers = [
155
- 'https://dns.google/resolve',
156
- 'https://cloudflare-dns.com/dns-query'
157
- ];
148
+ const defaultDnsServers = ["https://dns.google/resolve", "https://cloudflare-dns.com/dns-query"];
158
149
  async function dnsLookup(name, type, dnsServers = defaultDnsServers) {
159
- if (!dnsServers.length) {
160
- throw new Error('No DNS servers provided for lookup');
161
- }
162
- type = type.toUpperCase();
163
- console.log(`Performing DNS lookup for ${type} record of ${name} using servers: ${dnsServers.join(', ')}`);
164
- try {
165
- // Use Promise.race to get the first successful response
166
- return await raceSuccess(dnsServers.map(server => dnsResolver(server, name, type)));
167
- }
168
- catch (error) {
169
- console.error(`Failed to resolve DNS TXT record for ${name} using any server: ${error.message}`);
170
- throw new Error(`DNS lookup failed for ${name} (${type})`); // Re-throw a more specific error
171
- }
150
+ if (!dnsServers.length) throw new Error("No DNS servers provided for lookup");
151
+ type = type.toUpperCase();
152
+ console.log(`Performing DNS lookup for ${type} record of ${name} using servers: ${dnsServers.join(", ")}`);
153
+ try {
154
+ return await raceSuccess(dnsServers.map((server) => dnsResolver(server, name, type)));
155
+ } catch (error) {
156
+ console.error(`Failed to resolve DNS TXT record for ${name} using any server: ${error.message}`);
157
+ throw new Error(`DNS lookup failed for ${name} (${type})`);
158
+ }
172
159
  }
173
160
  function fetchContentViaHttp(url) {
174
- return new Observable((subscriber) => {
175
- let controller = new AbortController(); // For cancellation
176
- fetch(url, { signal: controller.signal })
177
- .then(response => {
178
- if (!response.ok) {
179
- // Don't complete here, let catchError handle it
180
- throw new Error(`HTTP error ${response.status} for ${url}: ${response.statusText}`);
181
- }
182
- return response.blob();
183
- })
184
- .then(blob => {
185
- if (!subscriber.closed) {
186
- subscriber.next(blob);
187
- subscriber.complete();
188
- }
189
- })
190
- .catch(error => {
191
- if (error.name !== 'AbortError' && !subscriber.closed) {
192
- console.warn(`Fetch error for ${url}:`, error);
193
- subscriber.error(error);
194
- }
195
- });
196
- // Cleanup function for when the observable is unsubscribed
197
- return () => {
198
- controller?.abort();
199
- controller = null; // Release reference
200
- };
201
- }).pipe(catchError(error => {
202
- // Log the error but return null to signal failure without stopping the race
203
- console.error(`Fetch failed for ${url}: ${error.message}`);
204
- return EMPTY; // Signal failure with null
205
- }));
161
+ return new Observable((subscriber) => {
162
+ let controller = new AbortController();
163
+ fetch(url, { signal: controller.signal }).then((response) => {
164
+ if (!response.ok) throw new Error(`HTTP error ${response.status} for ${url}: ${response.statusText}`);
165
+ return response.blob();
166
+ }).then((blob) => {
167
+ if (!subscriber.closed) {
168
+ subscriber.next(blob);
169
+ subscriber.complete();
170
+ }
171
+ }).catch((error) => {
172
+ if (error.name !== "AbortError" && !subscriber.closed) {
173
+ console.warn(`Fetch error for ${url}:`, error);
174
+ subscriber.error(error);
175
+ }
176
+ });
177
+ return () => {
178
+ controller?.abort();
179
+ controller = null;
180
+ };
181
+ }).pipe(catchError((error) => {
182
+ console.error(`Fetch failed for ${url}: ${error.message}`);
183
+ return EMPTY;
184
+ }));
206
185
  }
207
- const w3sIpfsGateway = cid => `https://${cid}.ipfs.w3s.link`;
208
- const storachaIpfsGateway = cid => `https://${cid}.ipfs.storacha.link`;
209
- const localPathIpfsGateway = cid => `${location.origin}/ipfs/${cid}`;
210
- const localSubDomainIpfsGateway = cid => `https://${cid}.ipfs.${location.hostname.split('.').slice(-2).join('.')}`;
186
+ const w3sIpfsGateway = (cid) => `https://${cid}.ipfs.w3s.link`;
187
+ const storachaIpfsGateway = (cid) => `https://${cid}.ipfs.storacha.link`;
188
+ const localPathIpfsGateway = (cid) => `${location.origin}/ipfs/${cid}`;
189
+ const localSubDomainIpfsGateway = (cid) => `https://${cid}.ipfs.${location.hostname.split(".").slice(-2).join(".")}`;
211
190
  const defaultIpfsGatewayServers = [
212
- w3sIpfsGateway,
213
- storachaIpfsGateway,
214
- localPathIpfsGateway,
215
- localSubDomainIpfsGateway
191
+ w3sIpfsGateway,
192
+ storachaIpfsGateway,
193
+ localPathIpfsGateway,
194
+ localSubDomainIpfsGateway
216
195
  ];
217
196
  function fetchCidContentViaHttp(cid, path, ipfsGatewayServers = defaultIpfsGatewayServers) {
218
- if (!ipfsGatewayServers.length) {
219
- throw new Error('No IPFS gateway servers provided for fetching content');
220
- }
221
- return race(...ipfsGatewayServers.map(fnc => fetchContentViaHttp(JoinPath(fnc(cid), path)).pipe(log(`fetch attempt for ${cid} via ${fnc.name} - ${fnc(cid)}`)))
222
- // Add more sources here if needed
223
- ).pipe(log(`Race winner for ${cid}`));
197
+ if (!ipfsGatewayServers.length) throw new Error("No IPFS gateway servers provided for fetching content");
198
+ return race(...ipfsGatewayServers.map((fnc) => fetchContentViaHttp(JoinPath(fnc(cid), path)).pipe(log(`fetch attempt for ${cid} via ${fnc.name} - ${fnc(cid)}`)))).pipe(log(`Race winner for ${cid}`));
224
199
  }
225
200
  async function fetchCidContent(cid, path, ipfsGatewayServers = defaultIpfsGatewayServers) {
226
- console.log(`Fetching content for CID: ${cid}`);
227
- // Example: Fetch from an IPFS gateway or other source
228
- // const gatewayUrl = `https://ipfs.io/ipfs/${cid}`;
229
- try {
230
- return await firstValueFrom(race(fetchCidContentViaHttp(cid, path, ipfsGatewayServers)), { defaultValue: null } // Return null if the stream completes empty
231
- );
232
- }
233
- catch (error) {
234
- console.error(`Error fetching or parsing content for CID ${cid}:`, error);
235
- return null; // Return null on error
236
- }
201
+ console.log(`Fetching content for CID: ${cid}`);
202
+ try {
203
+ return await firstValueFrom(race(fetchCidContentViaHttp(cid, path, ipfsGatewayServers)), { defaultValue: null });
204
+ } catch (error) {
205
+ console.error(`Error fetching or parsing content for CID ${cid}:`, error);
206
+ return null;
207
+ }
237
208
  }
238
209
  async function fetchCidContentAsJson(cid, path, _fetchCidContent = fetchCidContent, ipfsGatewayServers = defaultIpfsGatewayServers) {
239
- console.log(`Fetching JSON content for CID: ${cid}`);
240
- const blob = await _fetchCidContent(cid, path, ipfsGatewayServers);
241
- if (blob) {
242
- try {
243
- const text = await blob.text();
244
- return JSON.parse(text);
245
- }
246
- catch (error) {
247
- console.error(`Error parsing JSON content for CID ${cid}:`, error);
248
- return null; // Return null on error
249
- }
250
- }
251
- console.warn(`No blob available for CID ${cid}, cannot parse as JSON.`);
252
- return null; // Return null if blob is not available
210
+ console.log(`Fetching JSON content for CID: ${cid}`);
211
+ const blob = await _fetchCidContent(cid, path, ipfsGatewayServers);
212
+ if (blob) try {
213
+ const text = await blob.text();
214
+ return JSON.parse(text);
215
+ } catch (error) {
216
+ console.error(`Error parsing JSON content for CID ${cid}:`, error);
217
+ return null;
218
+ }
219
+ console.warn(`No blob available for CID ${cid}, cannot parse as JSON.`);
220
+ return null;
253
221
  }
254
-
255
222
  var ConfigLoadingStrategy;
256
- (function (ConfigLoadingStrategy) {
257
- ConfigLoadingStrategy["DEFAULT"] = "default";
258
- ConfigLoadingStrategy["FIFO"] = "fifo";
223
+ (function(ConfigLoadingStrategy) {
224
+ ConfigLoadingStrategy["DEFAULT"] = "default";
225
+ ConfigLoadingStrategy["FIFO"] = "fifo";
259
226
  })(ConfigLoadingStrategy || (ConfigLoadingStrategy = {}));
260
227
  var ConfigLoadMethod;
261
- (function (ConfigLoadMethod) {
262
- ConfigLoadMethod["FROM_URLS"] = "fromUrls";
263
- ConfigLoadMethod["FROM_LOCAL_STORAGE"] = "fromLocalStorage";
264
- ConfigLoadMethod["FROM_URL_PARAM"] = "fromUrlParam";
265
- ConfigLoadMethod["FROM_CID"] = "fromCid";
228
+ (function(ConfigLoadMethod) {
229
+ ConfigLoadMethod["FROM_URLS"] = "fromUrls";
230
+ ConfigLoadMethod["FROM_LOCAL_STORAGE"] = "fromLocalStorage";
231
+ ConfigLoadMethod["FROM_URL_PARAM"] = "fromUrlParam";
232
+ ConfigLoadMethod["FROM_CID"] = "fromCid";
266
233
  })(ConfigLoadMethod || (ConfigLoadMethod = {}));
267
- class ConfigService {
268
- static { this.onError = new ReplaySubject(1); }
269
- static { this.onRequestError = new ReplaySubject(1); }
270
- static { this.onErrorFnc = []; }
271
- static { this.onRequestErrorFnc = []; }
272
- static { this.Config = null; }
273
- /**
274
- * Static default values for the config object.
275
- * Will be overwritten by an dynamic config file specified in
276
- * the Urls array.
277
- */
278
- static { this.Defaults = {}; }
279
- /**
280
- * Any value definition in the Overwrites object will overwrite any
281
- * value form the Defaults values or dynamic config files
282
- */
283
- static { this.Overwrites = {}; }
284
- static { this.LocalStorageKey = 'rxap/config/local-config'; }
285
- /**
286
- * The errorHandler and requestInit of the last Load call. Used by SideLoad.
287
- */
288
- static { this.RequestOptions = {}; }
289
- /**
290
- * @deprecated instead use the url property of the ConfigLoadOptions
291
- */
292
- static { this.Urls = []; }
293
- constructor(config = null) {
294
- this.config = ConfigService.Config;
295
- if (config) {
296
- this.config = deepMerge(this.config ?? {}, config);
297
- }
298
- if (!this.config) {
299
- throw new Error('config not available');
300
- }
301
- }
302
- /**
303
- * Used to load the app config from a remote resource.
304
- *
305
- * Promise.all([ ConfigService.Load() ])
306
- * .then(() => platformBrowserDynamic().bootstrapModule(AppModule))
307
- * .catch(err => console.error(err))
308
- *
309
- */
310
- static async Load(options, environment) {
311
- options ??= {};
312
- this.RequestOptions = {
313
- errorHandler: options.errorHandler,
314
- requestInit: options.requestInit,
315
- };
316
- let config = deepMerge(this.Defaults, {});
317
- if (environment?.config) {
318
- if (typeof environment.config === 'string') {
319
- options.url = environment.config;
320
- }
321
- else {
322
- options.static = environment.config.static;
323
- options.url = environment.config.url;
324
- options.fromUrlParam = environment.config.fromUrlParam;
325
- options.fromLocalStorage = environment.config.fromLocalStorage;
326
- options.schema = environment.config.schema;
327
- options.strategy = environment.config.strategy ?? options.strategy;
328
- }
329
- }
330
- // Always merge static config first
331
- config = deepMerge(config, options?.static ?? {});
332
- // Determine the order of config sources to load
333
- const order = options.order ?? [
334
- ConfigLoadMethod.FROM_URLS,
335
- ConfigLoadMethod.FROM_LOCAL_STORAGE,
336
- ConfigLoadMethod.FROM_URL_PARAM,
337
- ConfigLoadMethod.FROM_CID,
338
- ];
339
- // If fromDns is enabled and FROM_CID is in the order, resolve CID first
340
- if (options.fromDns && order.includes(ConfigLoadMethod.FROM_CID) && !options.fromCid) {
341
- await this.loadConfigFromDns(options);
342
- }
343
- // Load configs from sources in the specified order
344
- let done = false;
345
- for (const method of order) {
346
- if (done) {
347
- break;
348
- }
349
- // Check if the source is enabled
350
- if (!this.isSourceEnabled(options, method)) {
351
- continue;
352
- }
353
- try {
354
- const loadedConfig = await this.loadConfigFromMethod(method, options, environment);
355
- if (loadedConfig) {
356
- config = deepMerge(config, loadedConfig);
357
- }
358
- // If using FIFO strategy, stop after first successful load
359
- if (options.strategy === ConfigLoadingStrategy.FIFO) {
360
- done = true;
361
- }
362
- }
363
- catch (error) {
364
- const methodName = this.getMethodName(method);
365
- if (options.strategy !== ConfigLoadingStrategy.FIFO) {
366
- console.error(`Could not load config from ${methodName}`, error);
367
- throw error;
368
- }
369
- else {
370
- console.warn(`Could not load config from ${methodName}: ${error.message}. Will try next strategy.`);
371
- }
372
- }
373
- }
374
- if (!done && order.length > 0) {
375
- console.warn('No config loading strategy succeeded. Using default config.');
376
- }
377
- // Always merge overwrites last
378
- config = deepMerge(config, this.Overwrites);
379
- console.debug('app config', config);
380
- this.Config = config;
381
- }
382
- static isSourceEnabled(options, method) {
383
- switch (method) {
384
- case ConfigLoadMethod.FROM_URLS:
385
- return options.fromUrls !== false;
386
- case ConfigLoadMethod.FROM_LOCAL_STORAGE:
387
- return options.fromLocalStorage !== false;
388
- case ConfigLoadMethod.FROM_URL_PARAM:
389
- return !!options.fromUrlParam;
390
- case ConfigLoadMethod.FROM_CID:
391
- return !!options.fromCid;
392
- default:
393
- return false;
394
- }
395
- }
396
- static async loadConfigFromMethod(method, options, environment) {
397
- switch (method) {
398
- case ConfigLoadMethod.FROM_URLS:
399
- return await this.loadConfigFromUrls(options, environment);
400
- case ConfigLoadMethod.FROM_LOCAL_STORAGE:
401
- return this.loadConfigFromLocalStorage(options);
402
- case ConfigLoadMethod.FROM_URL_PARAM:
403
- return this.loadConfigFromUrlParam(options);
404
- case ConfigLoadMethod.FROM_CID:
405
- return await this.loadConfigFromCid(options);
406
- default:
407
- return null;
408
- }
409
- }
410
- static getMethodName(method) {
411
- switch (method) {
412
- case ConfigLoadMethod.FROM_URLS:
413
- return 'urls';
414
- case ConfigLoadMethod.FROM_LOCAL_STORAGE:
415
- return 'local storage';
416
- case ConfigLoadMethod.FROM_URL_PARAM:
417
- return 'url param';
418
- case ConfigLoadMethod.FROM_CID:
419
- return 'cid';
420
- default:
421
- return 'unknown';
422
- }
423
- }
424
- static loadConfigFromUrlParam(options) {
425
- const param = typeof options.fromUrlParam === 'string' ? options.fromUrlParam : 'config';
426
- return this.LoadConfigDefaultFromUrlParam(param);
427
- }
428
- static loadConfigFromLocalStorage(options) {
429
- const localConfig = localStorage.getItem(ConfigService.LocalStorageKey);
430
- if (localConfig) {
431
- return JSON.parse(localConfig);
432
- }
433
- else {
434
- return {};
435
- }
436
- }
437
- static async loadConfigFromUrls(options, environment) {
438
- let config = {};
439
- const urls = (options?.url ? coerceArray(options.url) : ConfigService.Urls).map(url => {
440
- if (typeof url === 'function') {
441
- if (!environment) {
442
- throw new Error('environment is required when url is a function');
443
- }
444
- return coerceArray(url(environment));
445
- }
446
- return coerceArray(url);
447
- }).flat();
448
- for (const url of urls) {
449
- const loadedConfig = await this.loadConfig(url, true, options?.schema, options);
450
- const match = url.match(/config\.([a-zA-Z0-9.\-_]+)\.json/);
451
- if (match) {
452
- SetToObject(config, match[1], loadedConfig);
453
- }
454
- else {
455
- config = deepMerge(config, loadedConfig);
456
- }
457
- }
458
- return config;
459
- }
460
- static async loadConfigFromCid(options) {
461
- console.debug('Loading config from CID: ', options.fromCid);
462
- const ipfsGatewayFunctions = options.ipfsGatewayServers ?? [];
463
- if (!ipfsGatewayFunctions.length) {
464
- console.warn('No IPFS gateway servers provided for fetching content from CID');
465
- return;
466
- }
467
- try {
468
- const cidContent = await fetchCidContentAsJson(options.fromCid, undefined, options.fetchCidContent, ipfsGatewayFunctions);
469
- if (cidContent && typeof cidContent === 'object') {
470
- console.log(`Merging configuration from CID ${options.fromCid}.`, cidContent);
471
- // Merge CID content into the existing config object
472
- console.log('Configuration merged successfully.');
473
- return cidContent;
474
- }
475
- else if (cidContent) {
476
- console.warn(`Content fetched from CID ${options.fromCid} is not a mergeable object, skipping merge.`);
477
- }
478
- else {
479
- console.warn(`No content fetched or content was null for CID ${options.fromCid}.`);
480
- }
481
- }
482
- catch (error) {
483
- console.error(`Failed to fetch or process content for CID ${options.fromCid}: ${error.message}`);
484
- // Decide how to handle fetch/processing errors
485
- }
486
- }
487
- static async loadConfigFromDns(options) {
488
- console.debug('Loading config from DNS');
489
- const dnsServers = options.dnsServers ?? [];
490
- if (!dnsServers.length) {
491
- console.warn('No DNS servers provided for DNS lookup');
492
- return;
493
- }
494
- let domain = location.hostname;
495
- if (typeof options.fromDns === 'string') {
496
- domain = options.fromDns;
497
- }
498
- domain = CoercePrefix(domain, '_config.');
499
- try {
500
- console.log(`Attempting DNS lookup for domain: ${domain}`);
501
- const txtData = await dnsLookup(domain, 'TXT', dnsServers);
502
- console.log(`DNS TXT record data found: ${txtData}`);
503
- // Example CID extraction logic (adapt to your TXT record format)
504
- // This looks for IPFS CIDs (v0 'Qm...' or v1 'b...') potentially after 'ipfs://' or '/'
505
- const cidMatch = txtData.match(/(?:ipfs:\/\/|\/|^)([a-zA-Z0-9]{40,})$/);
506
- if (cidMatch && cidMatch[1]) {
507
- options.fromCid = cidMatch[1];
508
- console.log(`Extracted CID from DNS: ${options.fromCid}`);
509
- }
510
- else {
511
- console.warn(`Could not extract a valid CID format from DNS TXT data: "${txtData}"`);
512
- }
513
- }
514
- catch (error) {
515
- console.error(`DNS lookup for ${domain} failed: ${error.message}`);
516
- // Decide if failure is critical or recoverable
517
- }
518
- }
519
- static handleError(error) {
520
- this.onError.next(error);
521
- for (const fnc of this.onErrorFnc) {
522
- try {
523
- fnc(error);
524
- }
525
- catch (e) {
526
- console.error('Error in onErrorFnc', e);
527
- }
528
- }
529
- }
530
- static handleRequestError(response) {
531
- this.onRequestError.next(response);
532
- for (const fnc of this.onRequestErrorFnc) {
533
- try {
534
- fnc(response);
535
- }
536
- catch (e) {
537
- console.error('Error in onRequestErrorFnc', e);
538
- }
539
- }
540
- }
541
- static async loadConfig(url, required = false, schema, options = this.RequestOptions) {
542
- let config;
543
- let response;
544
- try {
545
- response = await fetch(url, options.requestInit);
546
- }
547
- catch (error) {
548
- return this.handleLoadError({
549
- kind: 'network',
550
- url,
551
- required,
552
- cause: error,
553
- message: `Could not fetch config from '${url}': ${error.message}`,
554
- }, options);
555
- }
556
- if (response.type === 'opaqueredirect') {
557
- return this.handleLoadError({
558
- kind: 'redirect',
559
- url,
560
- required,
561
- status: response.status,
562
- response,
563
- message: `Config request for '${url}' was redirected`,
564
- }, options);
565
- }
566
- if (!response.ok) {
567
- let message = `Config request results in non ok response for '${url}': (${response.status}) ${response.statusText}`;
568
- switch (response.status) {
569
- case 404:
570
- message = `Config not found at '${url}'`;
571
- break;
572
- case 405:
573
- message = `Config service is not started yet. Wait 30s and try again.`;
574
- break;
575
- case 401:
576
- message = `Unauthorized to fetch config from '${url}'`;
577
- break;
578
- }
579
- return this.handleLoadError({
580
- kind: 'http',
581
- url,
582
- required,
583
- status: response.status,
584
- response,
585
- message,
586
- }, options);
587
- }
588
- try {
589
- config = await response.json();
590
- }
591
- catch (error) {
592
- return this.handleLoadError({
593
- kind: 'parse',
594
- url,
595
- required,
596
- status: response.status,
597
- response,
598
- cause: error,
599
- message: `Could not parse config from '${url}' to a json object: ${error.message}`,
600
- }, options);
601
- }
602
- if (schema) {
603
- try {
604
- config = await schema.validateAsync(config);
605
- }
606
- catch (error) {
607
- return this.handleLoadError({
608
- kind: 'schema',
609
- url,
610
- required,
611
- status: response.status,
612
- response,
613
- cause: error,
614
- message: `Config from '${url}' is not valid: ${error.message}`,
615
- }, options);
616
- }
617
- }
618
- return config;
619
- }
620
- /**
621
- * Notifies the onError/onRequestError hooks (required urls only), calls the error handler and
622
- * throws for required urls. Resolves with null for optional urls.
623
- */
624
- static async handleLoadError(error, options) {
625
- if (error.required) {
626
- if (error.response && (error.kind === 'http' || error.kind === 'redirect')) {
627
- this.handleRequestError(error.response);
628
- }
629
- else {
630
- this.handleError(error.cause);
631
- }
632
- }
633
- const errorHandler = options.errorHandler ?? defaultConfigLoadErrorHandler;
634
- try {
635
- await errorHandler(error);
636
- }
637
- catch (e) {
638
- console.error('Error in config load error handler', e);
639
- }
640
- if (error.required) {
641
- throw new Error(error.message);
642
- }
643
- return null;
644
- }
645
- static LoadConfigDefaultFromUrlParam(param = 'config') {
646
- const queryString = window.location.search;
647
- const urlParams = new URLSearchParams(queryString);
648
- const configFromParams = {};
649
- for (const configParam of urlParams.getAll(param)) {
650
- try {
651
- const split = configParam.split(';');
652
- if (split.length === 2) {
653
- const keyPath = split[0];
654
- const value = split[1];
655
- SetObjectValue(configFromParams, keyPath, value);
656
- }
657
- }
658
- catch (e) {
659
- console.warn(`Parsing of url config param failed for '${configParam}': ${e.message}`);
660
- }
661
- }
662
- return configFromParams;
663
- }
664
- static async SideLoad(url, propertyPath, required, schema, options = this.RequestOptions) {
665
- if (!this.Config) {
666
- throw new Error('Config side load is only possible after the initial config load.');
667
- }
668
- const config = await this.loadConfig(url, required, schema, options);
669
- SetObjectValue(this.Config, propertyPath, config);
670
- console.debug(`Side loaded config for '${propertyPath}' successful`, this.Config);
671
- }
672
- static Get(path, defaultValue, config = this.Config) {
673
- if (!config) {
674
- throw new Error('config not loaded');
675
- }
676
- let configValue = config;
677
- if (typeof path !== 'string') {
678
- throw new Error('The config property path is not a string');
679
- }
680
- for (const fragment of path.split('.')) {
681
- if (configValue && typeof configValue === 'object' && fragment in configValue) {
682
- configValue = configValue[fragment];
683
- }
684
- else {
685
- if (defaultValue !== undefined) {
686
- return defaultValue;
687
- }
688
- console.debug(`Config with path '${path}' not found`);
689
- return undefined;
690
- }
691
- }
692
- return configValue;
693
- }
694
- setLocalConfig(config) {
695
- localStorage.setItem(ConfigService.LocalStorageKey, JSON.stringify(config));
696
- }
697
- clearLocalConfig() {
698
- localStorage.removeItem(ConfigService.LocalStorageKey);
699
- }
700
- get(propertyPath, defaultValue) {
701
- return ConfigService.Get(propertyPath, defaultValue, this.config);
702
- }
703
- getOrThrow(propertyPath, defaultValue) {
704
- const value = ConfigService.Get(propertyPath, defaultValue, this.config);
705
- if (value === undefined) {
706
- throw new Error(`Could not find config in path '${propertyPath}'`);
707
- }
708
- return value;
709
- }
710
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.9", ngImport: i0, type: ConfigService, deps: [{ token: RXAP_CONFIG, optional: true }], target: i0.ɵɵFactoryTarget.Injectable }); }
711
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.9", ngImport: i0, type: ConfigService, providedIn: 'root' }); }
712
- }
713
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.9", ngImport: i0, type: ConfigService, decorators: [{
714
- type: Injectable,
715
- args: [{
716
- providedIn: 'root',
717
- }]
718
- }], ctorParameters: () => [{ type: undefined, decorators: [{
719
- type: Optional
720
- }, {
721
- type: Inject,
722
- args: [RXAP_CONFIG]
723
- }] }] });
724
-
234
+ var ConfigService = class ConfigService {
235
+ static {
236
+ this.onError = new ReplaySubject(1);
237
+ }
238
+ static {
239
+ this.onRequestError = new ReplaySubject(1);
240
+ }
241
+ static {
242
+ this.onErrorFnc = [];
243
+ }
244
+ static {
245
+ this.onRequestErrorFnc = [];
246
+ }
247
+ static {
248
+ this.Config = null;
249
+ }
250
+ static {
251
+ this.Defaults = {};
252
+ }
253
+ static {
254
+ this.Overwrites = {};
255
+ }
256
+ static {
257
+ this.LocalStorageKey = "rxap/config/local-config";
258
+ }
259
+ static {
260
+ this.RequestOptions = {};
261
+ }
262
+ static {
263
+ this.Urls = [];
264
+ }
265
+ constructor(config = null) {
266
+ this.config = ConfigService.Config;
267
+ if (config) this.config = deepMerge(this.config ?? {}, config);
268
+ if (!this.config) throw new Error("config not available");
269
+ }
270
+ static async Load(options, environment) {
271
+ options ??= {};
272
+ this.RequestOptions = {
273
+ errorHandler: options.errorHandler,
274
+ requestInit: options.requestInit
275
+ };
276
+ let config = deepMerge(this.Defaults, {});
277
+ if (environment?.config) {
278
+ if (typeof environment.config === "string") options.url = environment.config;
279
+ else {
280
+ options.static = environment.config.static;
281
+ options.url = environment.config.url;
282
+ options.fromUrlParam = environment.config.fromUrlParam;
283
+ options.fromLocalStorage = environment.config.fromLocalStorage;
284
+ options.schema = environment.config.schema;
285
+ options.strategy = environment.config.strategy ?? options.strategy;
286
+ }
287
+ }
288
+ config = deepMerge(config, options?.static ?? {});
289
+ const order = options.order ?? [
290
+ ConfigLoadMethod.FROM_URLS,
291
+ ConfigLoadMethod.FROM_LOCAL_STORAGE,
292
+ ConfigLoadMethod.FROM_URL_PARAM,
293
+ ConfigLoadMethod.FROM_CID
294
+ ];
295
+ if (options.fromDns && order.includes(ConfigLoadMethod.FROM_CID) && !options.fromCid) await this.loadConfigFromDns(options);
296
+ let done = false;
297
+ for (const method of order) {
298
+ if (done) break;
299
+ if (!this.isSourceEnabled(options, method)) continue;
300
+ try {
301
+ const loadedConfig = await this.loadConfigFromMethod(method, options, environment);
302
+ if (loadedConfig) config = deepMerge(config, loadedConfig);
303
+ if (options.strategy === ConfigLoadingStrategy.FIFO) done = true;
304
+ } catch (error) {
305
+ const methodName = this.getMethodName(method);
306
+ if (options.strategy !== ConfigLoadingStrategy.FIFO) {
307
+ console.error(`Could not load config from ${methodName}`, error);
308
+ throw error;
309
+ } else console.warn(`Could not load config from ${methodName}: ${error.message}. Will try next strategy.`);
310
+ }
311
+ }
312
+ if (!done && order.length > 0) console.warn("No config loading strategy succeeded. Using default config.");
313
+ config = deepMerge(config, this.Overwrites);
314
+ console.debug("app config", config);
315
+ this.Config = config;
316
+ }
317
+ static isSourceEnabled(options, method) {
318
+ switch (method) {
319
+ case ConfigLoadMethod.FROM_URLS: return options.fromUrls !== false;
320
+ case ConfigLoadMethod.FROM_LOCAL_STORAGE: return options.fromLocalStorage !== false;
321
+ case ConfigLoadMethod.FROM_URL_PARAM: return !!options.fromUrlParam;
322
+ case ConfigLoadMethod.FROM_CID: return !!options.fromCid;
323
+ default: return false;
324
+ }
325
+ }
326
+ static async loadConfigFromMethod(method, options, environment) {
327
+ switch (method) {
328
+ case ConfigLoadMethod.FROM_URLS: return await this.loadConfigFromUrls(options, environment);
329
+ case ConfigLoadMethod.FROM_LOCAL_STORAGE: return this.loadConfigFromLocalStorage(options);
330
+ case ConfigLoadMethod.FROM_URL_PARAM: return this.loadConfigFromUrlParam(options);
331
+ case ConfigLoadMethod.FROM_CID: return await this.loadConfigFromCid(options);
332
+ default: return null;
333
+ }
334
+ }
335
+ static getMethodName(method) {
336
+ switch (method) {
337
+ case ConfigLoadMethod.FROM_URLS: return "urls";
338
+ case ConfigLoadMethod.FROM_LOCAL_STORAGE: return "local storage";
339
+ case ConfigLoadMethod.FROM_URL_PARAM: return "url param";
340
+ case ConfigLoadMethod.FROM_CID: return "cid";
341
+ default: return "unknown";
342
+ }
343
+ }
344
+ static loadConfigFromUrlParam(options) {
345
+ const param = typeof options.fromUrlParam === "string" ? options.fromUrlParam : "config";
346
+ return this.LoadConfigDefaultFromUrlParam(param);
347
+ }
348
+ static loadConfigFromLocalStorage(options) {
349
+ const localConfig = localStorage.getItem(ConfigService.LocalStorageKey);
350
+ if (localConfig) return JSON.parse(localConfig);
351
+ else return {};
352
+ }
353
+ static async loadConfigFromUrls(options, environment) {
354
+ let config = {};
355
+ const urls = (options?.url ? coerceArray(options.url) : ConfigService.Urls).map((url) => {
356
+ if (typeof url === "function") {
357
+ if (!environment) throw new Error("environment is required when url is a function");
358
+ return coerceArray(url(environment));
359
+ }
360
+ return coerceArray(url);
361
+ }).flat();
362
+ for (const url of urls) {
363
+ const loadedConfig = await this.loadConfig(url, true, options?.schema, options);
364
+ const match = url.match(/config\.([a-zA-Z0-9.\-_]+)\.json/);
365
+ if (match) SetToObject(config, match[1], loadedConfig);
366
+ else config = deepMerge(config, loadedConfig);
367
+ }
368
+ return config;
369
+ }
370
+ static async loadConfigFromCid(options) {
371
+ console.debug("Loading config from CID: ", options.fromCid);
372
+ const ipfsGatewayFunctions = options.ipfsGatewayServers ?? [];
373
+ if (!ipfsGatewayFunctions.length) {
374
+ console.warn("No IPFS gateway servers provided for fetching content from CID");
375
+ return;
376
+ }
377
+ try {
378
+ const cidContent = await fetchCidContentAsJson(options.fromCid, void 0, options.fetchCidContent, ipfsGatewayFunctions);
379
+ if (cidContent && typeof cidContent === "object") {
380
+ console.log(`Merging configuration from CID ${options.fromCid}.`, cidContent);
381
+ console.log("Configuration merged successfully.");
382
+ return cidContent;
383
+ } else if (cidContent) console.warn(`Content fetched from CID ${options.fromCid} is not a mergeable object, skipping merge.`);
384
+ else console.warn(`No content fetched or content was null for CID ${options.fromCid}.`);
385
+ } catch (error) {
386
+ console.error(`Failed to fetch or process content for CID ${options.fromCid}: ${error.message}`);
387
+ }
388
+ }
389
+ static async loadConfigFromDns(options) {
390
+ console.debug("Loading config from DNS");
391
+ const dnsServers = options.dnsServers ?? [];
392
+ if (!dnsServers.length) {
393
+ console.warn("No DNS servers provided for DNS lookup");
394
+ return;
395
+ }
396
+ let domain = location.hostname;
397
+ if (typeof options.fromDns === "string") domain = options.fromDns;
398
+ domain = CoercePrefix(domain, "_config.");
399
+ try {
400
+ console.log(`Attempting DNS lookup for domain: ${domain}`);
401
+ const txtData = await dnsLookup(domain, "TXT", dnsServers);
402
+ console.log(`DNS TXT record data found: ${txtData}`);
403
+ const cidMatch = txtData.match(/(?:ipfs:\/\/|\/|^)([a-zA-Z0-9]{40,})$/);
404
+ if (cidMatch && cidMatch[1]) {
405
+ options.fromCid = cidMatch[1];
406
+ console.log(`Extracted CID from DNS: ${options.fromCid}`);
407
+ } else console.warn(`Could not extract a valid CID format from DNS TXT data: "${txtData}"`);
408
+ } catch (error) {
409
+ console.error(`DNS lookup for ${domain} failed: ${error.message}`);
410
+ }
411
+ }
412
+ static handleError(error) {
413
+ this.onError.next(error);
414
+ for (const fnc of this.onErrorFnc) try {
415
+ fnc(error);
416
+ } catch (e) {
417
+ console.error("Error in onErrorFnc", e);
418
+ }
419
+ }
420
+ static handleRequestError(response) {
421
+ this.onRequestError.next(response);
422
+ for (const fnc of this.onRequestErrorFnc) try {
423
+ fnc(response);
424
+ } catch (e) {
425
+ console.error("Error in onRequestErrorFnc", e);
426
+ }
427
+ }
428
+ static async loadConfig(url, required = false, schema, options = this.RequestOptions) {
429
+ let config;
430
+ let response;
431
+ try {
432
+ response = await fetch(url, options.requestInit);
433
+ } catch (error) {
434
+ return this.handleLoadError({
435
+ kind: "network",
436
+ url,
437
+ required,
438
+ cause: error,
439
+ message: `Could not fetch config from '${url}': ${error.message}`
440
+ }, options);
441
+ }
442
+ if (response.type === "opaqueredirect") return this.handleLoadError({
443
+ kind: "redirect",
444
+ url,
445
+ required,
446
+ status: response.status,
447
+ response,
448
+ message: `Config request for '${url}' was redirected`
449
+ }, options);
450
+ if (!response.ok) {
451
+ let message = `Config request results in non ok response for '${url}': (${response.status}) ${response.statusText}`;
452
+ switch (response.status) {
453
+ case 404:
454
+ message = `Config not found at '${url}'`;
455
+ break;
456
+ case 405:
457
+ message = `Config service is not started yet. Wait 30s and try again.`;
458
+ break;
459
+ case 401: message = `Unauthorized to fetch config from '${url}'`;
460
+ }
461
+ return this.handleLoadError({
462
+ kind: "http",
463
+ url,
464
+ required,
465
+ status: response.status,
466
+ response,
467
+ message
468
+ }, options);
469
+ }
470
+ try {
471
+ config = await response.json();
472
+ } catch (error) {
473
+ return this.handleLoadError({
474
+ kind: "parse",
475
+ url,
476
+ required,
477
+ status: response.status,
478
+ response,
479
+ cause: error,
480
+ message: `Could not parse config from '${url}' to a json object: ${error.message}`
481
+ }, options);
482
+ }
483
+ if (schema) try {
484
+ config = await schema.validateAsync(config);
485
+ } catch (error) {
486
+ return this.handleLoadError({
487
+ kind: "schema",
488
+ url,
489
+ required,
490
+ status: response.status,
491
+ response,
492
+ cause: error,
493
+ message: `Config from '${url}' is not valid: ${error.message}`
494
+ }, options);
495
+ }
496
+ return config;
497
+ }
498
+ static async handleLoadError(error, options) {
499
+ if (error.required) {
500
+ if (error.response && (error.kind === "http" || error.kind === "redirect")) this.handleRequestError(error.response);
501
+ else this.handleError(error.cause);
502
+ }
503
+ const errorHandler = options.errorHandler ?? defaultConfigLoadErrorHandler;
504
+ try {
505
+ await errorHandler(error);
506
+ } catch (e) {
507
+ console.error("Error in config load error handler", e);
508
+ }
509
+ if (error.required) throw new Error(error.message);
510
+ return null;
511
+ }
512
+ static LoadConfigDefaultFromUrlParam(param = "config") {
513
+ const queryString = window.location.search;
514
+ const urlParams = new URLSearchParams(queryString);
515
+ const configFromParams = {};
516
+ for (const configParam of urlParams.getAll(param)) try {
517
+ const split = configParam.split(";");
518
+ if (split.length === 2) {
519
+ const keyPath = split[0];
520
+ const value = split[1];
521
+ SetObjectValue(configFromParams, keyPath, value);
522
+ }
523
+ } catch (e) {
524
+ console.warn(`Parsing of url config param failed for '${configParam}': ${e.message}`);
525
+ }
526
+ return configFromParams;
527
+ }
528
+ static async SideLoad(url, propertyPath, required, schema, options = this.RequestOptions) {
529
+ if (!this.Config) throw new Error("Config side load is only possible after the initial config load.");
530
+ const config = await this.loadConfig(url, required, schema, options);
531
+ SetObjectValue(this.Config, propertyPath, config);
532
+ console.debug(`Side loaded config for '${propertyPath}' successful`, this.Config);
533
+ }
534
+ static Get(path, defaultValue, config = this.Config) {
535
+ if (!config) throw new Error("config not loaded");
536
+ let configValue = config;
537
+ if (typeof path !== "string") throw new Error("The config property path is not a string");
538
+ for (const fragment of path.split(".")) if (configValue && typeof configValue === "object" && fragment in configValue) configValue = configValue[fragment];
539
+ else {
540
+ if (defaultValue !== void 0) return defaultValue;
541
+ console.debug(`Config with path '${path}' not found`);
542
+ return;
543
+ }
544
+ return configValue;
545
+ }
546
+ setLocalConfig(config) {
547
+ localStorage.setItem(ConfigService.LocalStorageKey, JSON.stringify(config));
548
+ }
549
+ clearLocalConfig() {
550
+ localStorage.removeItem(ConfigService.LocalStorageKey);
551
+ }
552
+ get(propertyPath, defaultValue) {
553
+ return ConfigService.Get(propertyPath, defaultValue, this.config);
554
+ }
555
+ getOrThrow(propertyPath, defaultValue) {
556
+ const value = ConfigService.Get(propertyPath, defaultValue, this.config);
557
+ if (value === void 0) throw new Error(`Could not find config in path '${propertyPath}'`);
558
+ return value;
559
+ }
560
+ static {
561
+ this.ɵfac = i0.ɵɵngDeclareFactory({
562
+ minVersion: "12.0.0",
563
+ version: "22.3.0",
564
+ ngImport: i0,
565
+ type: ConfigService,
566
+ deps: [{
567
+ token: RXAP_CONFIG,
568
+ optional: true
569
+ }],
570
+ target: i0.ɵɵFactoryTarget.Injectable
571
+ });
572
+ }
573
+ static {
574
+ this.ɵprov = i0.ɵɵngDeclareInjectable({
575
+ minVersion: "12.0.0",
576
+ version: "22.3.0",
577
+ ngImport: i0,
578
+ type: ConfigService,
579
+ providedIn: "root"
580
+ });
581
+ }
582
+ };
583
+ i0.ɵɵngDeclareClassMetadata({
584
+ minVersion: "12.0.0",
585
+ version: "22.3.0",
586
+ ngImport: i0,
587
+ type: ConfigService,
588
+ decorators: [{
589
+ type: Injectable,
590
+ args: [{ providedIn: "root" }]
591
+ }],
592
+ ctorParameters: () => [{
593
+ type: void 0,
594
+ decorators: [{ type: Optional }, {
595
+ type: Inject,
596
+ args: [RXAP_CONFIG]
597
+ }]
598
+ }]
599
+ });
725
600
  function ProvideConfig(config = {}) {
726
- return {
727
- provide: RXAP_CONFIG,
728
- useValue: config,
729
- };
601
+ return {
602
+ provide: RXAP_CONFIG,
603
+ useValue: config
604
+ };
730
605
  }
731
-
732
- // region
733
- // endregion
734
-
735
- /**
736
- * Generated bundle index. Do not edit.
737
- */
738
-
739
606
  export { ConfigLoadMethod, ConfigLoaderService, ConfigLoadingStrategy, ConfigService, ConfigTestingService, ProvideConfig, RXAP_CONFIG, defaultConfigLoadErrorHandler, defaultDnsServers, defaultIpfsGatewayServers, dnsLookup, dnsResolver, fetchCidContent, fetchCidContentAsJson, fetchCidContentViaHttp, fetchContentViaHttp, localPathIpfsGateway, localSubDomainIpfsGateway, raceSuccess, showConfigLoadError, storachaIpfsGateway, w3sIpfsGateway };
740
- //# sourceMappingURL=rxap-config.mjs.map
607
+
608
+ //# sourceMappingURL=rxap-config.mjs.map