@o3r/components 15.3.0-prerelease.9 → 15.3.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,337 +1,324 @@
1
- import * as i0 from '@angular/core';
2
- import { inject, Injector, Injectable, NgModule, makeEnvironmentProviders } from '@angular/core';
3
- import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
4
- import { Store, select } from '@ngrx/store';
5
- import { DynamicContentService } from '@o3r/dynamic-content';
6
- import { LoggerService } from '@o3r/logger';
7
- import { Subject, from, switchMap, of, map, startWith, distinctUntilChanged, combineLatest, withLatestFrom, firstValueFrom, EMPTY } from 'rxjs';
8
- import { selectPlaceholderTemplateEntities, selectPlaceholderRequestEntities, deletePlaceholderTemplateEntity, setPlaceholderTemplateEntity, updatePlaceholderRequestEntity, setPlaceholderRequestEntityFromUrl, selectPlaceholderRequestEntityUsage, failPlaceholderRequestEntity, cancelPlaceholderRequest, PlaceholderRequestStoreModule, PlaceholderTemplateStoreModule, providePlaceholderRequestStore, providePlaceholderTemplateStore } from '@o3r/components';
9
- import * as i1 from '@ngrx/effects';
10
- import { Actions, createEffect, ofType, EffectsModule, provideEffects } from '@ngrx/effects';
11
- import { fromApiEffectSwitchMapById } from '@o3r/core';
12
- import { RulesEngineRunnerService } from '@o3r/rules-engine';
13
- import { JSONPath } from 'jsonpath-plus';
14
- import { map as map$1, distinctUntilChanged as distinctUntilChanged$1, switchMap as switchMap$1, take } from 'rxjs/operators';
15
-
16
- /** ActionUpdatePlaceholderBlock */
17
- const RULES_ENGINE_PLACEHOLDER_UPDATE_ACTION_TYPE = 'UPDATE_PLACEHOLDER';
18
-
19
- /**
20
- * Service to handle async PlaceholderTemplate actions
21
- */
22
- class PlaceholderRulesEngineActionHandler {
23
- constructor() {
24
- this.logger = inject(LoggerService);
25
- this.injector = inject(Injector);
26
- // Prefer `@o3r/transloco`, fall back to `@o3r/localization`; both are optional peer dependencies.
27
- // TODO: use `injectAsync` to resolve the optional `LocalizationService` token once migrated to ng22
28
- // TODO: remove the dynamic-import fallback and inject the `LocalizationService` from the single supported translation package in v16
29
- this.translationService = import('@o3r/transloco')
30
- .then((mod) => this.injector.get(mod.LocalizationService, null))
31
- .catch(() => null)
32
- .then((service) => service ?? import('@o3r/localization')
33
- .then((mod) => this.injector.get(mod.LocalizationService, null) ?? undefined)
34
- .catch(() => undefined));
35
- this.placeholdersActions$ = new Subject();
36
- /** @inheritdoc */
37
- this.supportingActions = [RULES_ENGINE_PLACEHOLDER_UPDATE_ACTION_TYPE];
38
- const store = inject(Store);
39
- const lang$ = from(this.translationService).pipe(switchMap((translationService) => {
40
- if (!translationService) {
41
- return of(null);
42
- }
43
- const translateService = translationService.getTranslateService();
44
- // `@o3r/localization` (ngx-translate) exposes `onLangChange`, while `@o3r/transloco` (transloco) exposes `langChanges$`
45
- const langChange$ = translateService.onLangChange
46
- ? translateService.onLangChange.pipe(map(({ lang }) => lang))
47
- : translateService.langChanges$;
48
- return langChange$.pipe(startWith(translationService.getCurrentLanguage()), distinctUntilChanged());
49
- }));
50
- const filteredActions$ = combineLatest([
51
- lang$,
52
- this.placeholdersActions$.pipe(distinctUntilChanged((prev, next) => JSON.stringify(prev) === JSON.stringify(next)))
53
- ]).pipe(withLatestFrom(combineLatest([store.pipe(select(selectPlaceholderTemplateEntities)), store.pipe(select(selectPlaceholderRequestEntities))])), map(([langAndTemplatesUrls, storedPlaceholdersAndRequests]) => {
54
- const [lang, placeholderActions] = langAndTemplatesUrls;
55
- const storedPlaceholders = storedPlaceholdersAndRequests[0] || {};
56
- const storedPlaceholderRequests = storedPlaceholdersAndRequests[1] || {};
57
- const placeholderNewRequests = [];
58
- // Stores all raw Urls used from the current engine execution
59
- const usedUrls = {};
60
- // Get all Urls that needs to be resolved from current rules engine output
61
- const placeholdersTemplates = placeholderActions.reduce((acc, placeholderAction) => {
62
- const placeholdersTemplateUrl = {
63
- rawUrl: placeholderAction.templateUrl,
64
- priority: placeholderAction.priority
65
- };
66
- if (acc[placeholderAction.placeholderId]) {
67
- acc[placeholderAction.placeholderId].push(placeholdersTemplateUrl);
68
- }
69
- else {
70
- acc[placeholderAction.placeholderId] = [placeholdersTemplateUrl];
71
- }
72
- const resolvedUrl = this.resolveUrlWithLang(placeholderAction.templateUrl, lang);
73
- // Filters duplicates and resolved urls that are already in the store
74
- if (!usedUrls[placeholderAction.templateUrl] && (!storedPlaceholderRequests[placeholderAction.templateUrl]
75
- || storedPlaceholderRequests[placeholderAction.templateUrl].resolvedUrl !== resolvedUrl)) {
76
- placeholderNewRequests.push({
77
- rawUrl: placeholderAction.templateUrl,
78
- resolvedUrl: this.resolveUrlWithLang(placeholderAction.templateUrl, lang)
79
- });
80
- }
81
- usedUrls[placeholderAction.templateUrl] = true;
82
- return acc;
83
- }, {});
84
- // Urls not used anymore and not already disabled
85
- const placeholderRequestsToDisable = [];
86
- // Urls used that were disabled
87
- const placeholderRequestsToEnable = [];
88
- Object.keys(storedPlaceholderRequests).forEach((storedPlaceholderRequestRawUrl) => {
89
- const usedFromEngineIteration = usedUrls[storedPlaceholderRequestRawUrl];
90
- const usedFromStore = (storedPlaceholderRequests && storedPlaceholderRequests[storedPlaceholderRequestRawUrl]) ? storedPlaceholderRequests[storedPlaceholderRequestRawUrl].used : false;
91
- if (!usedFromEngineIteration && usedFromStore) {
92
- placeholderRequestsToDisable.push(storedPlaceholderRequestRawUrl);
93
- }
94
- else if (usedFromEngineIteration && !usedFromStore) {
95
- placeholderRequestsToEnable.push(storedPlaceholderRequestRawUrl);
96
- }
97
- });
98
- // Placeholder that are no longer filled by the current engine execution output will be cleared
99
- const placeholdersTemplatesToBeCleanedUp = Object.keys(storedPlaceholders)
100
- .filter((placeholderId) => !placeholdersTemplates[placeholderId]);
101
- const placeholdersTemplatesToBeSet = Object.keys(placeholdersTemplates).reduce((changedPlaceholderTemplates, placeholderTemplateId) => {
102
- // Caching if the placeholder template already exists with the same urls
103
- if (!storedPlaceholders[placeholderTemplateId]
104
- || !(JSON.stringify(storedPlaceholders[placeholderTemplateId].urlsWithPriority) === JSON.stringify(placeholdersTemplates[placeholderTemplateId]))) {
105
- changedPlaceholderTemplates.push({
106
- id: placeholderTemplateId,
107
- urlsWithPriority: placeholdersTemplates[placeholderTemplateId]
108
- });
109
- }
110
- return changedPlaceholderTemplates;
111
- }, []);
112
- return {
113
- placeholdersTemplatesToBeCleanedUp,
114
- placeholderRequestsToDisable,
115
- placeholderRequestsToEnable,
116
- placeholdersTemplatesToBeSet,
117
- placeholderNewRequests
118
- };
119
- }));
120
- filteredActions$.pipe(takeUntilDestroyed()).subscribe((placeholdersUpdates) => {
121
- placeholdersUpdates.placeholdersTemplatesToBeCleanedUp.forEach((placeholderId) => store.dispatch(deletePlaceholderTemplateEntity({
122
- id: placeholderId
123
- })));
124
- placeholdersUpdates.placeholdersTemplatesToBeSet.forEach((placeholdersTemplateToBeSet) => {
125
- store.dispatch(setPlaceholderTemplateEntity({ entity: placeholdersTemplateToBeSet }));
126
- });
127
- placeholdersUpdates.placeholderRequestsToDisable.forEach((placeholderRequestToDisable) => {
128
- store.dispatch(updatePlaceholderRequestEntity({ entity: { id: placeholderRequestToDisable, used: false } }));
129
- });
130
- placeholdersUpdates.placeholderRequestsToEnable.forEach((placeholderRequestToEnable) => {
131
- store.dispatch(updatePlaceholderRequestEntity({ entity: { id: placeholderRequestToEnable, used: true } }));
132
- });
133
- placeholdersUpdates.placeholderNewRequests.forEach((placeholderNewRequest) => {
134
- store.dispatch(setPlaceholderRequestEntityFromUrl({
135
- resolvedUrl: placeholderNewRequest.resolvedUrl,
136
- id: placeholderNewRequest.rawUrl,
137
- call: this.retrieveTemplate(placeholderNewRequest.resolvedUrl)
138
- }));
139
- });
140
- });
141
- }
142
- /**
143
- * Localize the url, replacing the language marker
144
- * @param url
145
- * @param language
146
- */
147
- resolveUrlWithLang(url, language) {
148
- if (!language && url.includes('[LANGUAGE]')) {
149
- this.logger.warn(`Missing language when trying to resolve ${url}`);
150
- }
151
- return language ? url.replace(/\[LANGUAGE]/g, language) : url;
152
- }
153
- /**
154
- * Retrieve template as json from a given url
155
- * @param url
156
- */
157
- async retrieveTemplate(url) {
158
- const resolvedUrl$ = this.injector.get(DynamicContentService, null, { optional: true })?.getContentPathStream(url) || of(url);
159
- const fullUrl = await firstValueFrom(resolvedUrl$);
160
- return fetch(fullUrl).then((response) => response.json());
161
- }
162
- /** @inheritdoc */
163
- executeActions(actions) {
164
- const templates = actions.map((action) => ({
165
- placeholderId: action.placeholderId,
166
- templateUrl: action.value,
167
- priority: action.priority || 0
168
- }));
169
- this.placeholdersActions$.next(templates);
170
- }
171
- /** @nocollapse */ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: PlaceholderRulesEngineActionHandler, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
172
- /** @nocollapse */ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: PlaceholderRulesEngineActionHandler }); }
173
- }
174
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: PlaceholderRulesEngineActionHandler, decorators: [{
175
- type: Injectable
176
- }], ctorParameters: () => [] });
177
-
178
- /**
179
- * Service to handle async PlaceholderTemplate actions
180
- */
181
- class PlaceholderTemplateResponseEffect {
182
- constructor() {
183
- this.actions$ = inject(Actions);
184
- this.store = inject(Store);
185
- this.rulesEngineService = inject(RulesEngineRunnerService, { optional: true });
186
- this.dynamicContentService = inject(DynamicContentService, { optional: true });
187
- this.injector = inject(Injector);
188
- // Prefer `@o3r/transloco`, fall back to `@o3r/localization`; both are optional peer dependencies.
189
- // TODO: use `injectAsync` to resolve the optional `LocalizationService` token once migrated to ng22
190
- // TODO: remove the dynamic-import fallback and inject the `LocalizationService` from the single supported translation package in v16
191
- this.translationService = import('@o3r/transloco')
192
- .then((mod) => this.injector.get(mod.LocalizationService, null))
193
- .catch(() => null)
194
- .then((service) => service ?? import('@o3r/localization')
195
- .then((mod) => this.injector.get(mod.LocalizationService, null) ?? undefined)
196
- .catch(() => undefined));
197
- /**
198
- * Set the PlaceholderRequest entity with the reply content, dispatch failPlaceholderRequestEntity if it catches a failure
199
- * Handles the rendering of the HTML content from the template and creates the combine latest from facts list if needed
200
- * Disables unused templates refresh if used is false in the store
201
- */
202
- this.setPlaceholderRequestEntityFromUrl$ = createEffect(() => this.actions$.pipe(ofType(setPlaceholderRequestEntityFromUrl), fromApiEffectSwitchMapById((templateResponse, action) => {
203
- const facts = templateResponse.vars ? Object.entries(templateResponse.vars).filter(([, variable]) => variable.type === 'fact') : [];
204
- const factsStreamsList = this.rulesEngineService
205
- ? facts.map(([varName, fact]) => this.rulesEngineService.engine.retrieveOrCreateFactStream(fact.value).pipe(map$1((factValue) => ({
206
- varName,
207
- factName: fact.value,
208
- // eslint-disable-next-line new-cap -- naming convention imposed by jsonpath-plus
209
- factValue: (fact.path && factValue) ? JSONPath({ wrap: false, json: factValue, path: fact.path }) : factValue
210
- })), distinctUntilChanged$1((previous, current) => previous.factValue === current.factValue)))
211
- : [];
212
- const factsStreamsList$ = factsStreamsList.length > 0 ? combineLatest(factsStreamsList) : of([]);
213
- return combineLatest([factsStreamsList$, this.store.select(selectPlaceholderRequestEntityUsage(action.id)).pipe(distinctUntilChanged$1())]).pipe(switchMap$1(([factsUsedInTemplate, placeholderRequestUsage]) => {
214
- if (!placeholderRequestUsage) {
215
- return EMPTY;
216
- }
217
- return this.getRenderedHTML$(templateResponse.template, templateResponse.vars, factsUsedInTemplate).pipe(map$1(({ renderedTemplate, unknownTypeFound }) =>
218
- // Update instead of set because used already set by the update from url action
219
- updatePlaceholderRequestEntity({
220
- entity: {
221
- ...templateResponse,
222
- resolvedUrl: action.resolvedUrl,
223
- id: action.id,
224
- renderedTemplate,
225
- unknownTypeFound
226
- },
227
- requestId: action.requestId
228
- })));
229
- }));
230
- }, (error, action) => of(failPlaceholderRequestEntity({ ids: [action.id], error, requestId: action.requestId })), (requestIdPayload, action) => cancelPlaceholderRequest({ ...requestIdPayload, id: action.id }))));
231
- }
232
- /**
233
- * Renders the html template, replacing facts and urls and localizationKeys
234
- * @param template
235
- * @param vars
236
- * @param facts
237
- */
238
- getRenderedHTML$(template, vars, facts) {
239
- let unknownTypeFound = false;
240
- const factMapFromVars = (facts || []).reduce((mapping, fact) => {
241
- mapping[fact.varName] = fact.factValue;
242
- return mapping;
243
- }, {});
244
- const replacements$ = [];
245
- if (vars && template) {
246
- for (const varName in vars) {
247
- if (Object.prototype.hasOwnProperty.call(vars, varName)) {
248
- const ejsVar = new RegExp(`<%=\\s*${varName}\\s*%>`, 'g');
249
- switch (vars[varName].type) {
250
- case 'relativeUrl': {
251
- replacements$.push(this.dynamicContentService?.getMediaPathStream(vars[varName].value).pipe(take(1), map$1((value) => ({ ejsVar, value }))) || of({ ejsVar, value: vars[varName].value }));
252
- break;
253
- }
254
- case 'fullUrl': {
255
- template = template.replace(ejsVar, vars[varName].value);
256
- break;
257
- }
258
- case 'fact': {
259
- template = template.replace(ejsVar, factMapFromVars[varName] ?? '');
260
- break;
261
- }
262
- case 'localisation': {
263
- const linkedParams = (Object.entries(vars[varName].parameters || {})).reduce((acc, [paramKey, paramValue]) => {
264
- acc[paramKey] = factMapFromVars[paramValue];
265
- return acc;
266
- }, {});
267
- replacements$.push(from(this.translationService).pipe(switchMap$1((translationService) => translationService
268
- ? translationService.translate(vars[varName].value, linkedParams).pipe(map$1((value) => (value ? { ejsVar, value } : null)))
269
- : of(null))));
270
- break;
271
- }
272
- default: {
273
- unknownTypeFound = true;
274
- break;
275
- }
276
- }
277
- }
278
- }
279
- }
280
- return replacements$.length > 0 && !!template
281
- ? combineLatest(replacements$).pipe(map$1((replacements) => ({
282
- renderedTemplate: replacements.reduce((acc, replacement) => replacement ? acc.replace(replacement.ejsVar, replacement.value) : acc, template),
283
- unknownTypeFound
284
- })))
285
- : of({ renderedTemplate: template, unknownTypeFound });
286
- }
287
- /** @nocollapse */ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: PlaceholderTemplateResponseEffect, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
288
- /** @nocollapse */ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: PlaceholderTemplateResponseEffect }); }
289
- }
290
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: PlaceholderTemplateResponseEffect, decorators: [{
291
- type: Injectable
292
- }] });
293
-
294
- /**
295
- * @deprecated Will be removed in v16. Use {@link providePlaceholderRulesEngineAction} instead.
296
- */
297
- class PlaceholderRulesEngineActionModule {
298
- /** @nocollapse */ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: PlaceholderRulesEngineActionModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
299
- /** @nocollapse */ static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "22.2.0", ngImport: i0, type: PlaceholderRulesEngineActionModule, imports: [i1.EffectsFeatureModule, PlaceholderRequestStoreModule,
300
- PlaceholderTemplateStoreModule] }); }
301
- /** @nocollapse */ static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: PlaceholderRulesEngineActionModule, providers: [
302
- PlaceholderRulesEngineActionHandler
303
- ], imports: [EffectsModule.forFeature([PlaceholderTemplateResponseEffect]),
304
- PlaceholderRequestStoreModule,
305
- PlaceholderTemplateStoreModule] }); }
306
- }
307
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: PlaceholderRulesEngineActionModule, decorators: [{
308
- type: NgModule,
309
- args: [{
310
- imports: [
311
- EffectsModule.forFeature([PlaceholderTemplateResponseEffect]),
312
- PlaceholderRequestStoreModule,
313
- PlaceholderTemplateStoreModule
314
- ],
315
- providers: [
316
- PlaceholderRulesEngineActionHandler
317
- ]
318
- }]
319
- }] });
320
- /**
321
- * Provide placeholder rules engine action handler.
322
- */
1
+ import * as i0 from "@angular/core";
2
+ import { Injectable, Injector, NgModule, inject, makeEnvironmentProviders } from "@angular/core";
3
+ import { takeUntilDestroyed } from "@angular/core/rxjs-interop";
4
+ import { Store, select } from "@ngrx/store";
5
+ import { DynamicContentService } from "@o3r/dynamic-content";
6
+ import { LoggerService } from "@o3r/logger";
7
+ import { EMPTY, Subject, combineLatest, distinctUntilChanged, firstValueFrom, from, map, of, startWith, switchMap, withLatestFrom } from "rxjs";
8
+ import { PlaceholderRequestStoreModule, PlaceholderTemplateStoreModule, cancelPlaceholderRequest, deletePlaceholderTemplateEntity, failPlaceholderRequestEntity, providePlaceholderRequestStore, providePlaceholderTemplateStore, selectPlaceholderRequestEntities, selectPlaceholderRequestEntityUsage, selectPlaceholderTemplateEntities, setPlaceholderRequestEntityFromUrl, setPlaceholderTemplateEntity, updatePlaceholderRequestEntity } from "@o3r/components";
9
+ import * as i1 from "@ngrx/effects";
10
+ import { Actions, EffectsModule, createEffect, ofType, provideEffects } from "@ngrx/effects";
11
+ import { fromApiEffectSwitchMapById } from "@o3r/core";
12
+ import { RulesEngineRunnerService } from "@o3r/rules-engine";
13
+ import { JSONPath } from "jsonpath-plus";
14
+ import { distinctUntilChanged as distinctUntilChanged$1, map as map$1, switchMap as switchMap$1, take } from "rxjs/operators";
15
+ const RULES_ENGINE_PLACEHOLDER_UPDATE_ACTION_TYPE = "UPDATE_PLACEHOLDER";
16
+ var PlaceholderRulesEngineActionHandler = class PlaceholderRulesEngineActionHandler {
17
+ constructor() {
18
+ this.logger = inject(LoggerService);
19
+ this.injector = inject(Injector);
20
+ this.translationService = import("@o3r/transloco").then((mod) => this.injector.get(mod.LocalizationService, null)).catch(() => null).then((service) => service ?? import("@o3r/localization").then((mod) => this.injector.get(mod.LocalizationService, null) ?? void 0).catch(() => void 0));
21
+ this.placeholdersActions$ = new Subject();
22
+ this.supportingActions = [RULES_ENGINE_PLACEHOLDER_UPDATE_ACTION_TYPE];
23
+ const store = inject(Store);
24
+ const lang$ = from(this.translationService).pipe(switchMap((translationService) => {
25
+ if (!translationService) return of(null);
26
+ const translateService = translationService.getTranslateService();
27
+ return (translateService.onLangChange ? translateService.onLangChange.pipe(map(({ lang }) => lang)) : translateService.langChanges$).pipe(startWith(translationService.getCurrentLanguage()), distinctUntilChanged());
28
+ }));
29
+ combineLatest([lang$, this.placeholdersActions$.pipe(distinctUntilChanged((prev, next) => JSON.stringify(prev) === JSON.stringify(next)))]).pipe(withLatestFrom(combineLatest([store.pipe(select(selectPlaceholderTemplateEntities)), store.pipe(select(selectPlaceholderRequestEntities))])), map(([langAndTemplatesUrls, storedPlaceholdersAndRequests]) => {
30
+ const [lang, placeholderActions] = langAndTemplatesUrls;
31
+ const storedPlaceholders = storedPlaceholdersAndRequests[0] || {};
32
+ const storedPlaceholderRequests = storedPlaceholdersAndRequests[1] || {};
33
+ const placeholderNewRequests = [];
34
+ const usedUrls = {};
35
+ const placeholdersTemplates = placeholderActions.reduce((acc, placeholderAction) => {
36
+ const placeholdersTemplateUrl = {
37
+ rawUrl: placeholderAction.templateUrl,
38
+ priority: placeholderAction.priority
39
+ };
40
+ if (acc[placeholderAction.placeholderId]) acc[placeholderAction.placeholderId].push(placeholdersTemplateUrl);
41
+ else acc[placeholderAction.placeholderId] = [placeholdersTemplateUrl];
42
+ const resolvedUrl = this.resolveUrlWithLang(placeholderAction.templateUrl, lang);
43
+ if (!usedUrls[placeholderAction.templateUrl] && (!storedPlaceholderRequests[placeholderAction.templateUrl] || storedPlaceholderRequests[placeholderAction.templateUrl].resolvedUrl !== resolvedUrl)) placeholderNewRequests.push({
44
+ rawUrl: placeholderAction.templateUrl,
45
+ resolvedUrl: this.resolveUrlWithLang(placeholderAction.templateUrl, lang)
46
+ });
47
+ usedUrls[placeholderAction.templateUrl] = true;
48
+ return acc;
49
+ }, {});
50
+ const placeholderRequestsToDisable = [];
51
+ const placeholderRequestsToEnable = [];
52
+ Object.keys(storedPlaceholderRequests).forEach((storedPlaceholderRequestRawUrl) => {
53
+ const usedFromEngineIteration = usedUrls[storedPlaceholderRequestRawUrl];
54
+ const usedFromStore = storedPlaceholderRequests && storedPlaceholderRequests[storedPlaceholderRequestRawUrl] ? storedPlaceholderRequests[storedPlaceholderRequestRawUrl].used : false;
55
+ if (!usedFromEngineIteration && usedFromStore) placeholderRequestsToDisable.push(storedPlaceholderRequestRawUrl);
56
+ else if (usedFromEngineIteration && !usedFromStore) placeholderRequestsToEnable.push(storedPlaceholderRequestRawUrl);
57
+ });
58
+ return {
59
+ placeholdersTemplatesToBeCleanedUp: Object.keys(storedPlaceholders).filter((placeholderId) => !placeholdersTemplates[placeholderId]),
60
+ placeholderRequestsToDisable,
61
+ placeholderRequestsToEnable,
62
+ placeholdersTemplatesToBeSet: Object.keys(placeholdersTemplates).reduce((changedPlaceholderTemplates, placeholderTemplateId) => {
63
+ if (!storedPlaceholders[placeholderTemplateId] || !(JSON.stringify(storedPlaceholders[placeholderTemplateId].urlsWithPriority) === JSON.stringify(placeholdersTemplates[placeholderTemplateId]))) changedPlaceholderTemplates.push({
64
+ id: placeholderTemplateId,
65
+ urlsWithPriority: placeholdersTemplates[placeholderTemplateId]
66
+ });
67
+ return changedPlaceholderTemplates;
68
+ }, []),
69
+ placeholderNewRequests
70
+ };
71
+ })).pipe(takeUntilDestroyed()).subscribe((placeholdersUpdates) => {
72
+ placeholdersUpdates.placeholdersTemplatesToBeCleanedUp.forEach((placeholderId) => store.dispatch(deletePlaceholderTemplateEntity({ id: placeholderId })));
73
+ placeholdersUpdates.placeholdersTemplatesToBeSet.forEach((placeholdersTemplateToBeSet) => {
74
+ store.dispatch(setPlaceholderTemplateEntity({ entity: placeholdersTemplateToBeSet }));
75
+ });
76
+ placeholdersUpdates.placeholderRequestsToDisable.forEach((placeholderRequestToDisable) => {
77
+ store.dispatch(updatePlaceholderRequestEntity({ entity: {
78
+ id: placeholderRequestToDisable,
79
+ used: false
80
+ } }));
81
+ });
82
+ placeholdersUpdates.placeholderRequestsToEnable.forEach((placeholderRequestToEnable) => {
83
+ store.dispatch(updatePlaceholderRequestEntity({ entity: {
84
+ id: placeholderRequestToEnable,
85
+ used: true
86
+ } }));
87
+ });
88
+ placeholdersUpdates.placeholderNewRequests.forEach((placeholderNewRequest) => {
89
+ store.dispatch(setPlaceholderRequestEntityFromUrl({
90
+ resolvedUrl: placeholderNewRequest.resolvedUrl,
91
+ id: placeholderNewRequest.rawUrl,
92
+ call: this.retrieveTemplate(placeholderNewRequest.resolvedUrl)
93
+ }));
94
+ });
95
+ });
96
+ }
97
+ resolveUrlWithLang(url, language) {
98
+ if (!language && url.includes("[LANGUAGE]")) this.logger.warn(`Missing language when trying to resolve ${url}`);
99
+ return language ? url.replace(/\[LANGUAGE]/g, language) : url;
100
+ }
101
+ async retrieveTemplate(url) {
102
+ const resolvedUrl$ = this.injector.get(DynamicContentService, null, { optional: true })?.getContentPathStream(url) || of(url);
103
+ const fullUrl = await firstValueFrom(resolvedUrl$);
104
+ return fetch(fullUrl).then((response) => response.json());
105
+ }
106
+ executeActions(actions) {
107
+ const templates = actions.map((action) => ({
108
+ placeholderId: action.placeholderId,
109
+ templateUrl: action.value,
110
+ priority: action.priority || 0
111
+ }));
112
+ this.placeholdersActions$.next(templates);
113
+ }
114
+ static {
115
+ this.ɵfac = i0.ɵɵngDeclareFactory({
116
+ minVersion: "12.0.0",
117
+ version: "22.2.3",
118
+ ngImport: i0,
119
+ type: PlaceholderRulesEngineActionHandler,
120
+ deps: [],
121
+ target: i0.ɵɵFactoryTarget.Injectable
122
+ });
123
+ }
124
+ static {
125
+ this.ɵprov = i0.ɵɵngDeclareInjectable({
126
+ minVersion: "12.0.0",
127
+ version: "22.2.3",
128
+ ngImport: i0,
129
+ type: PlaceholderRulesEngineActionHandler
130
+ });
131
+ }
132
+ };
133
+ i0.ɵɵngDeclareClassMetadata({
134
+ minVersion: "12.0.0",
135
+ version: "22.2.3",
136
+ ngImport: i0,
137
+ type: PlaceholderRulesEngineActionHandler,
138
+ decorators: [{ type: Injectable }],
139
+ ctorParameters: () => []
140
+ });
141
+ var PlaceholderTemplateResponseEffect = class PlaceholderTemplateResponseEffect {
142
+ constructor() {
143
+ this.actions$ = inject(Actions);
144
+ this.store = inject(Store);
145
+ this.rulesEngineService = inject(RulesEngineRunnerService, { optional: true });
146
+ this.dynamicContentService = inject(DynamicContentService, { optional: true });
147
+ this.injector = inject(Injector);
148
+ this.translationService = import("@o3r/transloco").then((mod) => this.injector.get(mod.LocalizationService, null)).catch(() => null).then((service) => service ?? import("@o3r/localization").then((mod) => this.injector.get(mod.LocalizationService, null) ?? void 0).catch(() => void 0));
149
+ this.setPlaceholderRequestEntityFromUrl$ = createEffect(() => this.actions$.pipe(ofType(setPlaceholderRequestEntityFromUrl), fromApiEffectSwitchMapById((templateResponse, action) => {
150
+ const facts = templateResponse.vars ? Object.entries(templateResponse.vars).filter(([, variable]) => variable.type === "fact") : [];
151
+ const factsStreamsList = this.rulesEngineService ? facts.map(([varName, fact]) => this.rulesEngineService.engine.retrieveOrCreateFactStream(fact.value).pipe(map$1((factValue) => ({
152
+ varName,
153
+ factName: fact.value,
154
+ factValue: fact.path && factValue ? JSONPath({
155
+ wrap: false,
156
+ json: factValue,
157
+ path: fact.path
158
+ }) : factValue
159
+ })), distinctUntilChanged$1((previous, current) => previous.factValue === current.factValue))) : [];
160
+ const factsStreamsList$ = factsStreamsList.length > 0 ? combineLatest(factsStreamsList) : of([]);
161
+ return combineLatest([factsStreamsList$, this.store.select(selectPlaceholderRequestEntityUsage(action.id)).pipe(distinctUntilChanged$1())]).pipe(switchMap$1(([factsUsedInTemplate, placeholderRequestUsage]) => {
162
+ if (!placeholderRequestUsage) return EMPTY;
163
+ return this.getRenderedHTML$(templateResponse.template, templateResponse.vars, factsUsedInTemplate).pipe(map$1(({ renderedTemplate, unknownTypeFound }) => updatePlaceholderRequestEntity({
164
+ entity: {
165
+ ...templateResponse,
166
+ resolvedUrl: action.resolvedUrl,
167
+ id: action.id,
168
+ renderedTemplate,
169
+ unknownTypeFound
170
+ },
171
+ requestId: action.requestId
172
+ })));
173
+ }));
174
+ }, (error, action) => of(failPlaceholderRequestEntity({
175
+ ids: [action.id],
176
+ error,
177
+ requestId: action.requestId
178
+ })), (requestIdPayload, action) => cancelPlaceholderRequest({
179
+ ...requestIdPayload,
180
+ id: action.id
181
+ }))));
182
+ }
183
+ getRenderedHTML$(template, vars, facts) {
184
+ let unknownTypeFound = false;
185
+ const factMapFromVars = (facts || []).reduce((mapping, fact) => {
186
+ mapping[fact.varName] = fact.factValue;
187
+ return mapping;
188
+ }, {});
189
+ const replacements$ = [];
190
+ if (vars && template) {
191
+ for (const varName in vars) if (Object.prototype.hasOwnProperty.call(vars, varName)) {
192
+ const ejsVar = new RegExp(`<%=\\s*${varName}\\s*%>`, "g");
193
+ switch (vars[varName].type) {
194
+ case "relativeUrl":
195
+ replacements$.push(this.dynamicContentService?.getMediaPathStream(vars[varName].value).pipe(take(1), map$1((value) => ({
196
+ ejsVar,
197
+ value
198
+ }))) || of({
199
+ ejsVar,
200
+ value: vars[varName].value
201
+ }));
202
+ break;
203
+ case "fullUrl":
204
+ template = template.replace(ejsVar, vars[varName].value);
205
+ break;
206
+ case "fact":
207
+ template = template.replace(ejsVar, factMapFromVars[varName] ?? "");
208
+ break;
209
+ case "localisation": {
210
+ const linkedParams = Object.entries(vars[varName].parameters || {}).reduce((acc, [paramKey, paramValue]) => {
211
+ acc[paramKey] = factMapFromVars[paramValue];
212
+ return acc;
213
+ }, {});
214
+ replacements$.push(from(this.translationService).pipe(switchMap$1((translationService) => translationService ? translationService.translate(vars[varName].value, linkedParams).pipe(map$1((value) => value ? {
215
+ ejsVar,
216
+ value
217
+ } : null)) : of(null))));
218
+ break;
219
+ }
220
+ default: unknownTypeFound = true;
221
+ }
222
+ }
223
+ }
224
+ return replacements$.length > 0 && !!template ? combineLatest(replacements$).pipe(map$1((replacements) => ({
225
+ renderedTemplate: replacements.reduce((acc, replacement) => replacement ? acc.replace(replacement.ejsVar, replacement.value) : acc, template),
226
+ unknownTypeFound
227
+ }))) : of({
228
+ renderedTemplate: template,
229
+ unknownTypeFound
230
+ });
231
+ }
232
+ static {
233
+ this.ɵfac = i0.ɵɵngDeclareFactory({
234
+ minVersion: "12.0.0",
235
+ version: "22.2.3",
236
+ ngImport: i0,
237
+ type: PlaceholderTemplateResponseEffect,
238
+ deps: [],
239
+ target: i0.ɵɵFactoryTarget.Injectable
240
+ });
241
+ }
242
+ static {
243
+ this.ɵprov = i0.ɵɵngDeclareInjectable({
244
+ minVersion: "12.0.0",
245
+ version: "22.2.3",
246
+ ngImport: i0,
247
+ type: PlaceholderTemplateResponseEffect
248
+ });
249
+ }
250
+ };
251
+ i0.ɵɵngDeclareClassMetadata({
252
+ minVersion: "12.0.0",
253
+ version: "22.2.3",
254
+ ngImport: i0,
255
+ type: PlaceholderTemplateResponseEffect,
256
+ decorators: [{ type: Injectable }]
257
+ });
258
+ var PlaceholderRulesEngineActionModule = class PlaceholderRulesEngineActionModule {
259
+ static {
260
+ this.ɵfac = i0.ɵɵngDeclareFactory({
261
+ minVersion: "12.0.0",
262
+ version: "22.2.3",
263
+ ngImport: i0,
264
+ type: PlaceholderRulesEngineActionModule,
265
+ deps: [],
266
+ target: i0.ɵɵFactoryTarget.NgModule
267
+ });
268
+ }
269
+ static {
270
+ this.ɵmod = i0.ɵɵngDeclareNgModule({
271
+ minVersion: "14.0.0",
272
+ version: "22.2.3",
273
+ ngImport: i0,
274
+ type: PlaceholderRulesEngineActionModule,
275
+ imports: [
276
+ i1.EffectsFeatureModule,
277
+ PlaceholderRequestStoreModule,
278
+ PlaceholderTemplateStoreModule
279
+ ]
280
+ });
281
+ }
282
+ static {
283
+ this.ɵinj = i0.ɵɵngDeclareInjector({
284
+ minVersion: "12.0.0",
285
+ version: "22.2.3",
286
+ ngImport: i0,
287
+ type: PlaceholderRulesEngineActionModule,
288
+ providers: [PlaceholderRulesEngineActionHandler],
289
+ imports: [
290
+ EffectsModule.forFeature([PlaceholderTemplateResponseEffect]),
291
+ PlaceholderRequestStoreModule,
292
+ PlaceholderTemplateStoreModule
293
+ ]
294
+ });
295
+ }
296
+ };
297
+ i0.ɵɵngDeclareClassMetadata({
298
+ minVersion: "12.0.0",
299
+ version: "22.2.3",
300
+ ngImport: i0,
301
+ type: PlaceholderRulesEngineActionModule,
302
+ decorators: [{
303
+ type: NgModule,
304
+ args: [{
305
+ imports: [
306
+ EffectsModule.forFeature([PlaceholderTemplateResponseEffect]),
307
+ PlaceholderRequestStoreModule,
308
+ PlaceholderTemplateStoreModule
309
+ ],
310
+ providers: [PlaceholderRulesEngineActionHandler]
311
+ }]
312
+ }]
313
+ });
323
314
  function providePlaceholderRulesEngineAction() {
324
- return makeEnvironmentProviders([
325
- providePlaceholderRequestStore(),
326
- providePlaceholderTemplateStore(),
327
- provideEffects(PlaceholderTemplateResponseEffect),
328
- PlaceholderRulesEngineActionHandler
329
- ]);
315
+ return makeEnvironmentProviders([
316
+ providePlaceholderRequestStore(),
317
+ providePlaceholderTemplateStore(),
318
+ provideEffects(PlaceholderTemplateResponseEffect),
319
+ PlaceholderRulesEngineActionHandler
320
+ ]);
330
321
  }
331
-
332
- /**
333
- * Generated bundle index. Do not edit.
334
- */
335
-
336
322
  export { PlaceholderRulesEngineActionHandler, PlaceholderRulesEngineActionModule, RULES_ENGINE_PLACEHOLDER_UPDATE_ACTION_TYPE, providePlaceholderRulesEngineAction };
337
- //# sourceMappingURL=o3r-components-rules-engine.mjs.map
323
+
324
+ //# sourceMappingURL=o3r-components-rules-engine.mjs.map