UNPKG

@spartacus/core

Version:

Spartacus - the core framework

1,284 lines (1,235 loc) 1.11 MB
import * as i0 from '@angular/core'; import { inject, Injectable, InjectFlags, InjectionToken, isDevMode, PLATFORM_ID, Inject, Optional, NgModule, APP_INITIALIZER, Directive, Input, NgModuleFactory, Pipe } from '@angular/core'; import * as i1$2 from '@ngrx/store'; import { createFeatureSelector, createSelector, select, INIT, META_REDUCERS, StoreModule, combineReducers } from '@ngrx/store'; import { ReplaySubject, of, fromEvent, BehaviorSubject, iif, combineLatest, queueScheduler, throwError, Subscription, Observable, Subject, using, EMPTY, defer, from, zip, timer, asapScheduler, forkJoin, merge, isObservable } from 'rxjs'; import { take, map, debounceTime, startWith, distinctUntilChanged, filter, shareReplay, withLatestFrom, tap, switchMap, observeOn, catchError, exhaustMap, mapTo, share, pairwise, skipWhile, concatMap, mergeMap, publishReplay, switchMapTo, scan, skip, bufferCount, groupBy, distinctUntilKeyChanged, debounce, retry, finalize, pluck, audit, delay, takeUntil } from 'rxjs/operators'; import { __awaiter, __decorate, __rest } from 'tslib'; import * as i1 from 'angular-oauth2-oidc'; import { OAuthStorage, OAuthModule } from 'angular-oauth2-oidc'; import * as i6 from '@angular/common'; import { isPlatformBrowser, DOCUMENT, isPlatformServer, CommonModule, LOCATION_INITIALIZED, Location, DatePipe, getLocaleId, DecimalPipe } from '@angular/common'; import * as i1$1 from '@angular/router'; import { PRIMARY_OUTLET, NavigationEnd, DefaultUrlSerializer, Router, NavigationStart, NavigationError, NavigationCancel, UrlSerializer, RouterModule } from '@angular/router'; import * as i1$3 from '@angular/common/http'; import { HttpHeaders, HttpParams, HttpErrorResponse, HTTP_INTERCEPTORS, HttpClientModule, HttpResponse, HttpClient } from '@angular/common/http'; import * as i1$4 from '@ngrx/effects'; import { ofType, Effect, EffectsModule, createEffect } from '@ngrx/effects'; import { makeStateKey, TransferState, Meta } from '@angular/platform-browser'; import * as fromNgrxRouter from '@ngrx/router-store'; import { RouterStateSerializer, StoreRouterConnectingModule } from '@ngrx/router-store'; import i18nextHttpBackend from 'i18next-http-backend'; import i18next from 'i18next'; function isObject(item) { return item && typeof item === 'object' && !Array.isArray(item); } function deepMerge(target = {}, ...sources) { if (!sources.length) { return target; } const source = sources.shift() || {}; if (isObject(source)) { for (const key in source) { if (source[key] instanceof Date) { target[key] = source[key]; } else if (isObject(source[key])) { if (!target[key] || !isObject(target[key])) { target[key] = {}; } deepMerge(target[key], source[key]); } else { target[key] = source[key]; } } } return deepMerge(target, ...sources); } function configFactory() { return deepMerge({}, inject(DefaultConfig), inject(RootConfig)); } /** * Global Configuration, can be used to inject configuration to any part of the app */ class Config { } Config.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.0.5", ngImport: i0, type: Config, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); Config.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "12.0.5", ngImport: i0, type: Config, providedIn: 'root', useFactory: configFactory }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.0.5", ngImport: i0, type: Config, decorators: [{ type: Injectable, args: [{ providedIn: 'root', useFactory: configFactory, }] }] }); function defaultConfigFactory() { var _a; return deepMerge({}, ...((_a = inject(DefaultConfigChunk, InjectFlags.Optional)) !== null && _a !== void 0 ? _a : [])); } /** * Default Configuration token, used to build Global Configuration, built from DefaultConfigChunks */ const DefaultConfig = new InjectionToken('DefaultConfiguration', { providedIn: 'root', factory: defaultConfigFactory, }); function rootConfigFactory() { var _a; return deepMerge({}, ...((_a = inject(ConfigChunk, InjectFlags.Optional)) !== null && _a !== void 0 ? _a : [])); } /** * Root Configuration token, used to build Global Configuration, built from ConfigChunks */ const RootConfig = new InjectionToken('RootConfiguration', { providedIn: 'root', factory: rootConfigFactory, }); /** * Config chunk token, can be used to provide configuration chunk and contribute to the global configuration object. * Should not be used directly, use `provideConfig` or import `ConfigModule.withConfig` instead. */ const ConfigChunk = new InjectionToken('ConfigurationChunk'); /** * Config chunk token, can be used to provide configuration chunk and contribute to the default configuration. * Should not be used directly, use `provideDefaultConfig` or `provideDefaultConfigFactory` instead. * * General rule is, that all config provided in libraries should be provided as default config. */ const DefaultConfigChunk = new InjectionToken('DefaultConfigurationChunk'); /** * Helper function to provide configuration chunk using ConfigChunk token * * To provide default configuration in libraries provideDefaultConfig should be used instead. * * @param config Config object to merge with the global configuration */ function provideConfig(config = {}, defaultConfig = false) { return { provide: defaultConfig ? DefaultConfigChunk : ConfigChunk, useValue: config, multi: true, }; } /** * Helper function to provide configuration with factory function, using ConfigChunk token * * To provide default configuration in libraries provideDefaultConfigFactory should be used instead. * * @param configFactory Factory Function that will generate config object * @param deps Optional dependencies to a factory function */ function provideConfigFactory(configFactory, deps, defaultConfig = false) { return { provide: defaultConfig ? DefaultConfigChunk : ConfigChunk, useFactory: configFactory, multi: true, deps: deps, }; } /** * Helper function to provide default configuration chunk using DefaultConfigChunk token * * @param config Config object to merge with the default configuration */ function provideDefaultConfig(config = {}) { return { provide: DefaultConfigChunk, useValue: config, multi: true, }; } /** * Helper function to provide default configuration with factory function, using DefaultConfigChunk token * * @param configFactory Factory Function that will generate config object * @param deps Optional dependencies to a factory function */ function provideDefaultConfigFactory(configFactory, deps) { return { provide: DefaultConfigChunk, useFactory: configFactory, multi: true, deps: deps, }; } const defaultAnonymousConsentsConfig = { anonymousConsents: { registerConsent: 'MARKETING_NEWSLETTER', showLegalDescriptionInDialog: true, requiredConsents: [], consentManagementPage: { showAnonymousConsents: true, hideConsents: [], }, }, }; var CountryType; (function (CountryType) { CountryType["BILLING"] = "BILLING"; CountryType["SHIPPING"] = "SHIPPING"; })(CountryType || (CountryType = {})); var PromotionLocation; (function (PromotionLocation) { PromotionLocation["ActiveCart"] = "CART"; PromotionLocation["Checkout"] = "CHECKOUT"; PromotionLocation["Order"] = "ORDER"; PromotionLocation["SaveForLater"] = "SAVE_FOR_LATER"; PromotionLocation["SavedCart"] = "SAVED_CART"; })(PromotionLocation || (PromotionLocation = {})); var B2BPaymentTypeEnum; (function (B2BPaymentTypeEnum) { B2BPaymentTypeEnum["ACCOUNT_PAYMENT"] = "ACCOUNT"; B2BPaymentTypeEnum["CARD_PAYMENT"] = "CARD"; })(B2BPaymentTypeEnum || (B2BPaymentTypeEnum = {})); var CartValidationStatusCode; (function (CartValidationStatusCode) { CartValidationStatusCode["NO_STOCK"] = "noStock"; CartValidationStatusCode["LOW_STOCK"] = "lowStock"; CartValidationStatusCode["REVIEW_CONFIGURATION"] = "reviewConfiguration"; CartValidationStatusCode["PRICING_ERROR"] = "pricingError"; CartValidationStatusCode["UNRESOLVABLE_ISSUES"] = "unresolvableIssues"; })(CartValidationStatusCode || (CartValidationStatusCode = {})); var PageType; (function (PageType) { PageType["CONTENT_PAGE"] = "ContentPage"; PageType["PRODUCT_PAGE"] = "ProductPage"; PageType["CATEGORY_PAGE"] = "CategoryPage"; PageType["CATALOG_PAGE"] = "CatalogPage"; })(PageType || (PageType = {})); var CmsBannerCarouselEffect; (function (CmsBannerCarouselEffect) { CmsBannerCarouselEffect["FADE"] = "FADE"; CmsBannerCarouselEffect["ZOOM"] = "ZOOM"; CmsBannerCarouselEffect["CURTAIN"] = "CURTAINX"; CmsBannerCarouselEffect["TURNDOWN"] = "TURNDOWN"; })(CmsBannerCarouselEffect || (CmsBannerCarouselEffect = {})); var ANONYMOUS_CONSENT_STATUS; (function (ANONYMOUS_CONSENT_STATUS) { ANONYMOUS_CONSENT_STATUS["GIVEN"] = "GIVEN"; ANONYMOUS_CONSENT_STATUS["WITHDRAWN"] = "WITHDRAWN"; })(ANONYMOUS_CONSENT_STATUS || (ANONYMOUS_CONSENT_STATUS = {})); const ANONYMOUS_CONSENTS_HEADER = 'X-Anonymous-Consents'; var ImageType; (function (ImageType) { ImageType["PRIMARY"] = "PRIMARY"; ImageType["GALLERY"] = "GALLERY"; })(ImageType || (ImageType = {})); class HttpErrorModel { } var B2BUserRole; (function (B2BUserRole) { B2BUserRole["ADMIN"] = "b2badmingroup"; B2BUserRole["CUSTOMER"] = "b2bcustomergroup"; B2BUserRole["MANAGER"] = "b2bmanagergroup"; B2BUserRole["APPROVER"] = "b2bapprovergroup"; })(B2BUserRole || (B2BUserRole = {})); var NotificationType; (function (NotificationType) { NotificationType["BACK_IN_STOCK"] = "BACK_IN_STOCK"; })(NotificationType || (NotificationType = {})); var VariantType; (function (VariantType) { VariantType["SIZE"] = "ApparelSizeVariantProduct"; VariantType["STYLE"] = "ApparelStyleVariantProduct"; VariantType["COLOR"] = "ElectronicsColorVariantProduct"; })(VariantType || (VariantType = {})); var PriceType; (function (PriceType) { PriceType["BUY"] = "BUY"; PriceType["FROM"] = "FROM"; })(PriceType || (PriceType = {})); var VariantQualifier; (function (VariantQualifier) { VariantQualifier["SIZE"] = "size"; VariantQualifier["STYLE"] = "style"; VariantQualifier["COLOR"] = "color"; VariantQualifier["THUMBNAIL"] = "thumbnail"; VariantQualifier["PRODUCT"] = "product"; VariantQualifier["ROLLUP_PROPERTY"] = "rollupProperty"; })(VariantQualifier || (VariantQualifier = {})); var DaysOfWeek; (function (DaysOfWeek) { DaysOfWeek["MONDAY"] = "MONDAY"; DaysOfWeek["TUESDAY"] = "TUESDAY"; DaysOfWeek["WEDNESDAY"] = "WEDNESDAY"; DaysOfWeek["THURSDAY"] = "THURSDAY"; DaysOfWeek["FRIDAY"] = "FRIDAY"; DaysOfWeek["SATURDAY"] = "SATURDAY"; DaysOfWeek["SUNDAY"] = "SUNDAY"; })(DaysOfWeek || (DaysOfWeek = {})); const recurrencePeriod = { DAILY: 'DAILY', WEEKLY: 'WEEKLY', MONTHLY: 'MONTHLY', }; var ORDER_TYPE; (function (ORDER_TYPE) { ORDER_TYPE["PLACE_ORDER"] = "PLACE_ORDER"; ORDER_TYPE["SCHEDULE_REPLENISHMENT_ORDER"] = "SCHEDULE_REPLENISHMENT_ORDER"; })(ORDER_TYPE || (ORDER_TYPE = {})); const ENTITY_REMOVE_ACTION = '[ENTITY] REMOVE'; const ENTITY_REMOVE_ALL_ACTION = '[ENTITY] REMOVE ALL'; function entityMeta(type, id) { return { entityType: type, entityId: id, }; } function entityRemoveMeta(type, id) { return { entityId: id, entityType: type, entityRemove: true, }; } function entityRemoveAllMeta(type) { return { entityId: null, entityType: type, entityRemove: true, }; } class EntityRemoveAction { constructor(entityType, id) { this.type = ENTITY_REMOVE_ACTION; this.meta = entityRemoveMeta(entityType, id); } } class EntityRemoveAllAction { constructor(entityType) { this.type = ENTITY_REMOVE_ALL_ACTION; this.meta = entityRemoveAllMeta(entityType); } } const LOADER_LOAD_ACTION = '[LOADER] LOAD'; const LOADER_FAIL_ACTION = '[LOADER] FAIL'; const LOADER_SUCCESS_ACTION = '[LOADER] SUCCESS'; const LOADER_RESET_ACTION = '[LOADER] RESET'; function loadMeta(entityType) { return { entityType: entityType, loader: { load: true, }, }; } function failMeta(entityType, error) { return { entityType: entityType, loader: { error: error ? error : true, }, }; } function successMeta(entityType) { return { entityType: entityType, loader: { success: true, }, }; } function resetMeta(entityType) { return { entityType: entityType, loader: {}, }; } class LoaderLoadAction { constructor(entityType) { this.type = LOADER_LOAD_ACTION; this.meta = loadMeta(entityType); } } class LoaderFailAction { constructor(entityType, error) { this.type = LOADER_FAIL_ACTION; this.meta = failMeta(entityType, error); } } class LoaderSuccessAction { constructor(entityType) { this.type = LOADER_SUCCESS_ACTION; this.meta = successMeta(entityType); } } class LoaderResetAction { constructor(entityType) { this.type = LOADER_RESET_ACTION; this.meta = resetMeta(entityType); } } const ENTITY_LOAD_ACTION = '[ENTITY] LOAD'; const ENTITY_FAIL_ACTION = '[ENTITY] LOAD FAIL'; const ENTITY_SUCCESS_ACTION = '[ENTITY] LOAD SUCCESS'; const ENTITY_RESET_ACTION = '[ENTITY] RESET'; function entityLoadMeta(entityType, id) { return Object.assign(Object.assign({}, loadMeta(entityType)), entityMeta(entityType, id)); } function entityFailMeta(entityType, id, error) { return Object.assign(Object.assign({}, failMeta(entityType, error)), entityMeta(entityType, id)); } function entitySuccessMeta(entityType, id) { return Object.assign(Object.assign({}, successMeta(entityType)), entityMeta(entityType, id)); } function entityResetMeta(entityType, id) { return Object.assign(Object.assign({}, resetMeta(entityType)), entityMeta(entityType, id)); } class EntityLoadAction { constructor(entityType, id) { this.type = ENTITY_LOAD_ACTION; this.meta = entityLoadMeta(entityType, id); } } class EntityFailAction { constructor(entityType, id, error) { this.type = ENTITY_FAIL_ACTION; this.meta = entityFailMeta(entityType, id, error); } } class EntitySuccessAction { constructor(entityType, id, payload) { this.payload = payload; this.type = ENTITY_SUCCESS_ACTION; this.meta = entitySuccessMeta(entityType, id); } } class EntityLoaderResetAction { constructor(entityType, id) { this.type = ENTITY_RESET_ACTION; this.meta = entityResetMeta(entityType, id); } } const initialLoaderState = { loading: false, error: false, success: false, value: undefined, }; /** * Higher order reducer that adds generic loading flag to chunk of the state * * Utilizes "loader" meta field of actions to set specific flags for specific * action (LOAD, SUCCESS, FAIL, RESET) */ function loaderReducer(entityType, reducer) { return (state = initialLoaderState, action) => { if (action.meta && action.meta.loader && action.meta.entityType === entityType) { const entity = action.meta.loader; if (entity.load) { return Object.assign(Object.assign({}, state), { loading: true, value: reducer ? reducer(state.value, action) : state.value }); } else if (entity.error) { return Object.assign(Object.assign({}, state), { loading: false, error: true, success: false, value: reducer ? reducer(state.value, action) : undefined }); } else if (entity.success) { return Object.assign(Object.assign({}, state), { value: reducer ? reducer(state.value, action) : action.payload, loading: false, error: false, success: true }); } else { // reset state action return Object.assign(Object.assign({}, initialLoaderState), { value: reducer ? reducer(initialLoaderState.value, action) : initialLoaderState.value }); } } if (reducer) { const newValue = reducer(state.value, action); if (newValue !== state.value) { return Object.assign(Object.assign({}, state), { value: newValue }); } } return state; }; } function loaderValueSelector(state) { return state.value; } function loaderLoadingSelector(state) { return state.loading; } function loaderErrorSelector(state) { return state.error; } function loaderSuccessSelector(state) { return state.success; } function entityLoaderStateSelector(state, id) { return state.entities[id] || initialLoaderState; } function entityValueSelector(state, id) { const entityState = entityLoaderStateSelector(state, id); return loaderValueSelector(entityState); } function entityLoadingSelector(state, id) { const entityState = entityLoaderStateSelector(state, id); return loaderLoadingSelector(entityState); } function entityErrorSelector(state, id) { const entityState = entityLoaderStateSelector(state, id); return loaderErrorSelector(entityState); } function entitySuccessSelector(state, id) { const entityState = entityLoaderStateSelector(state, id); return loaderSuccessSelector(entityState); } const initialEntityState = { entities: {} }; /** * Higher order reducer for reusing reducer logic for multiple entities * * Utilizes entityId meta field to target entity by id in actions */ function entityReducer(entityType, reducer) { return (state = initialEntityState, action) => { let ids; let partitionPayload = false; if (action.meta && action.meta.entityType === entityType && action.meta.entityId !== undefined) { ids = [].concat(action.meta.entityId); // remove selected entities if (action.meta.entityRemove) { if (action.meta.entityId === null) { return initialEntityState; } else { let removed = false; const newEntities = Object.keys(state.entities).reduce((acc, cur) => { if (ids.includes(cur)) { removed = true; } else { acc[cur] = state.entities[cur]; } return acc; }, {}); return removed ? { entities: newEntities } : state; } } partitionPayload = Array.isArray(action.meta.entityId) && Array.isArray(action.payload); } else { ids = Object.keys(state.entities); } const entityUpdates = {}; for (let i = 0; i < ids.length; i++) { const id = ids[i]; const subAction = partitionPayload ? Object.assign(Object.assign({}, action), { payload: action.payload[i] }) : action; const newState = reducer(state.entities[id], subAction); if (newState) { entityUpdates[id] = newState; } } if (Object.keys(entityUpdates).length > 0) { return Object.assign(Object.assign({}, state), { entities: Object.assign(Object.assign({}, state.entities), entityUpdates) }); } return state; }; } /** * Higher order reducer that wraps LoaderReducer and EntityReducer enhancing * single state reducer to support multiple entities with generic loading flags */ function entityLoaderReducer(entityType, reducer) { return entityReducer(entityType, loaderReducer(entityType, reducer)); } const PROCESSES_INCREMENT_ACTION = '[PROCESSES LOADER] INCREMENT'; const PROCESSES_DECREMENT_ACTION = '[PROCESSES LOADER] DECREMENT'; const PROCESSES_LOADER_RESET_ACTION = '[PROCESSES LOADER] RESET'; function processesIncrementMeta(entityType) { return { entityType: entityType, loader: undefined, processesCountDiff: 1, }; } function processesDecrementMeta(entityType) { return { entityType: entityType, loader: undefined, processesCountDiff: -1, }; } function processesLoaderResetMeta(entityType) { // processes reset action is a reset action for loader reducer, but not the other way around return Object.assign(Object.assign({}, resetMeta(entityType)), { processesCountDiff: null }); } class ProcessesLoaderResetAction { constructor(entityType) { this.type = PROCESSES_LOADER_RESET_ACTION; this.meta = processesLoaderResetMeta(entityType); } } class ProcessesIncrementAction { constructor(entityType) { this.type = PROCESSES_INCREMENT_ACTION; this.meta = processesIncrementMeta(entityType); } } class ProcessesDecrementAction { constructor(entityType) { this.type = PROCESSES_DECREMENT_ACTION; this.meta = processesDecrementMeta(entityType); } } const ENTITY_PROCESSES_LOADER_RESET_ACTION = '[ENTITY] PROCESSES LOADER RESET'; const ENTITY_PROCESSES_INCREMENT_ACTION = '[ENTITY] PROCESSES INCREMENT'; const ENTITY_PROCESSES_DECREMENT_ACTION = '[ENTITY] PROCESSES DECREMENT'; function entityProcessesLoaderResetMeta(entityType, id) { return Object.assign(Object.assign({}, processesLoaderResetMeta(entityType)), entityMeta(entityType, id)); } function entityProcessesIncrementMeta(entityType, id) { return Object.assign(Object.assign({}, processesIncrementMeta(entityType)), entityMeta(entityType, id)); } function entityProcessesDecrementMeta(entityType, id) { return Object.assign(Object.assign({}, processesDecrementMeta(entityType)), entityMeta(entityType, id)); } class EntityProcessesLoaderResetAction { constructor(entityType, id) { this.type = ENTITY_PROCESSES_LOADER_RESET_ACTION; this.meta = entityProcessesLoaderResetMeta(entityType, id); } } class EntityProcessesIncrementAction { constructor(entityType, id) { this.type = ENTITY_PROCESSES_INCREMENT_ACTION; this.meta = entityProcessesIncrementMeta(entityType, id); } } class EntityProcessesDecrementAction { constructor(entityType, id) { this.type = ENTITY_PROCESSES_DECREMENT_ACTION; this.meta = entityProcessesDecrementMeta(entityType, id); } } function isStableSelector(state) { return state.processesCount === 0 && !state.loading; } function hasPendingProcessesSelector(state) { return state.processesCount > 0; } const initialProcessesState = { processesCount: 0, }; /** * Higher order reducer that adds processes count */ function processesLoaderReducer(entityType, reducer) { return (state = Object.assign(Object.assign({}, initialProcessesState), initialLoaderState), action) => { const loaderState = loaderReducer(entityType, reducer)(state, action); if (action.meta && action.meta.entityType === entityType) { const processesCountDiff = action.meta.processesCountDiff; if (isDevMode() && state.processesCount + processesCountDiff < 0) { console.error(`Action '${action.type}' sets processesCount to value < 0!\n` + 'Make sure to keep processesCount in sync.\n' + 'There should always be only one decrement action for each increment action.\n' + "Make sure that you don't reset state in between those actions.\n", action); } if (processesCountDiff) { return Object.assign(Object.assign({}, loaderState), { processesCount: state.processesCount ? state.processesCount + processesCountDiff : processesCountDiff }); } else if (processesCountDiff === null) { // reset action return Object.assign(Object.assign({}, loaderState), initialProcessesState); } } return loaderState; }; } const initialProcessesLoaderState = Object.assign(Object.assign({}, initialLoaderState), initialProcessesState); function entityHasPendingProcessesSelector(state, id) { const entityState = entityLoaderStateSelector(state, id); return hasPendingProcessesSelector(entityState); } function entityIsStableSelector(state, id) { const entityState = entityLoaderStateSelector(state, id); return isStableSelector(entityState); } function entityProcessesLoaderStateSelector(state, id) { return state.entities[id] || initialProcessesLoaderState; } /** * Higher order reducer that wraps ProcessesLoaderReducer and EntityReducer enhancing * single state reducer to support multiple entities with generic processesCount flag */ function entityProcessesLoaderReducer(entityType, reducer) { return entityReducer(entityType, processesLoaderReducer(entityType, reducer)); } function entitySelector(state, id) { return state.entities[id] || undefined; } const OBJECT_SEPARATOR = '.'; function getStateSliceValue(keys, state) { return keys .split(OBJECT_SEPARATOR) .reduce((previous, current) => (previous ? previous[current] : undefined), state); } function createShellObject(key, excludeKeys, value) { if (!key || !value || Object.keys(value).length === 0) { return {}; } const shell = key.split(OBJECT_SEPARATOR).reduceRight((acc, previous) => { return { [previous]: acc }; }, value); return handleExclusions(key, excludeKeys, shell); } function getStateSlice(keys, excludeKeys, state) { if (keys && keys.length === 0) { return {}; } let stateSlices = {}; for (const currentKey of keys) { const stateValue = getStateSliceValue(currentKey, state); const shell = createShellObject(currentKey, excludeKeys, stateValue); stateSlices = deepMerge(stateSlices, shell); } return stateSlices; } function handleExclusions(key, excludeKeys, value) { const exclusionKeys = getExclusionKeys(key, excludeKeys); if (exclusionKeys.length === 0) { return value; } const finalValue = deepMerge({}, value); for (const currentExclusionKey of exclusionKeys) { const exclusionChunksSplit = currentExclusionKey.split(OBJECT_SEPARATOR); let nestedTemp = finalValue; for (let i = 0; i < exclusionChunksSplit.length; i++) { const currentChunk = exclusionChunksSplit[i]; // last iteration if (i === exclusionChunksSplit.length - 1) { if (nestedTemp && nestedTemp[currentChunk]) { delete nestedTemp[currentChunk]; } } else { nestedTemp = nestedTemp[currentChunk]; } } } return finalValue; } function getExclusionKeys(key, excludeKeys) { if (!key || !excludeKeys) { return []; } const exclusionKeys = []; for (const exclusionKey of excludeKeys) { if (exclusionKey.includes(key)) { exclusionKeys.push(exclusionKey); } } return exclusionKeys; } function filterKeysByType(keys, type) { if (!keys) { return []; } return Object.keys(keys).filter((key) => keys[key] === type); } const ALL = 'all'; function serializeSearchConfig(config, id) { var _a, _b, _c; return `${id !== null && id !== void 0 ? id : ''}?pageSize=${(_a = config.pageSize) !== null && _a !== void 0 ? _a : ''}&currentPage=${(_b = config.currentPage) !== null && _b !== void 0 ? _b : ''}&sort=${(_c = config.sort) !== null && _c !== void 0 ? _c : ''}`; } function denormalizeSearch(state, params) { return denormalizeCustomB2BSearch(state.list, state.entities, params); } function denormalizeCustomB2BSearch(list, entities, params, id) { const serializedList = entityLoaderStateSelector(list, params ? serializeSearchConfig(params, id) : id !== null && id !== void 0 ? id : ALL); if (!serializedList.value || !serializedList.value.ids) { return serializedList; } const res = Object.assign({}, serializedList, { value: { values: serializedList.value.ids.map((code) => entityLoaderStateSelector(entities, code).value), }, }); if (params) { res.value.pagination = serializedList.value.pagination; res.value.sorts = serializedList.value.sorts; } return res; } function normalizeListPage(list, id) { const values = (list === null || list === void 0 ? void 0 : list.values) || []; const page = { ids: values.map((data) => data[id]), }; if (list.pagination) { page.pagination = list.pagination; } if (list.sorts) { page.sorts = list.sorts; } return { values, page }; } function serializeParams(params, searchConfig) { return [params, serializeSearchConfig(searchConfig)].toString(); } var utilsGroup = /*#__PURE__*/Object.freeze({ __proto__: null, getStateSlice: getStateSlice, ENTITY_LOAD_ACTION: ENTITY_LOAD_ACTION, ENTITY_FAIL_ACTION: ENTITY_FAIL_ACTION, ENTITY_SUCCESS_ACTION: ENTITY_SUCCESS_ACTION, ENTITY_RESET_ACTION: ENTITY_RESET_ACTION, entityLoadMeta: entityLoadMeta, entityFailMeta: entityFailMeta, entitySuccessMeta: entitySuccessMeta, entityResetMeta: entityResetMeta, EntityLoadAction: EntityLoadAction, EntityFailAction: EntityFailAction, EntitySuccessAction: EntitySuccessAction, EntityLoaderResetAction: EntityLoaderResetAction, entityLoaderStateSelector: entityLoaderStateSelector, entityValueSelector: entityValueSelector, entityLoadingSelector: entityLoadingSelector, entityErrorSelector: entityErrorSelector, entitySuccessSelector: entitySuccessSelector, entityLoaderReducer: entityLoaderReducer, ENTITY_PROCESSES_LOADER_RESET_ACTION: ENTITY_PROCESSES_LOADER_RESET_ACTION, ENTITY_PROCESSES_INCREMENT_ACTION: ENTITY_PROCESSES_INCREMENT_ACTION, ENTITY_PROCESSES_DECREMENT_ACTION: ENTITY_PROCESSES_DECREMENT_ACTION, entityProcessesLoaderResetMeta: entityProcessesLoaderResetMeta, entityProcessesIncrementMeta: entityProcessesIncrementMeta, entityProcessesDecrementMeta: entityProcessesDecrementMeta, EntityProcessesLoaderResetAction: EntityProcessesLoaderResetAction, EntityProcessesIncrementAction: EntityProcessesIncrementAction, EntityProcessesDecrementAction: EntityProcessesDecrementAction, entityHasPendingProcessesSelector: entityHasPendingProcessesSelector, entityIsStableSelector: entityIsStableSelector, entityProcessesLoaderStateSelector: entityProcessesLoaderStateSelector, entityProcessesLoaderReducer: entityProcessesLoaderReducer, ENTITY_REMOVE_ACTION: ENTITY_REMOVE_ACTION, ENTITY_REMOVE_ALL_ACTION: ENTITY_REMOVE_ALL_ACTION, entityMeta: entityMeta, entityRemoveMeta: entityRemoveMeta, entityRemoveAllMeta: entityRemoveAllMeta, EntityRemoveAction: EntityRemoveAction, EntityRemoveAllAction: EntityRemoveAllAction, entitySelector: entitySelector, initialEntityState: initialEntityState, entityReducer: entityReducer, LOADER_LOAD_ACTION: LOADER_LOAD_ACTION, LOADER_FAIL_ACTION: LOADER_FAIL_ACTION, LOADER_SUCCESS_ACTION: LOADER_SUCCESS_ACTION, LOADER_RESET_ACTION: LOADER_RESET_ACTION, loadMeta: loadMeta, failMeta: failMeta, successMeta: successMeta, resetMeta: resetMeta, LoaderLoadAction: LoaderLoadAction, LoaderFailAction: LoaderFailAction, LoaderSuccessAction: LoaderSuccessAction, LoaderResetAction: LoaderResetAction, loaderValueSelector: loaderValueSelector, loaderLoadingSelector: loaderLoadingSelector, loaderErrorSelector: loaderErrorSelector, loaderSuccessSelector: loaderSuccessSelector, initialLoaderState: initialLoaderState, loaderReducer: loaderReducer, PROCESSES_INCREMENT_ACTION: PROCESSES_INCREMENT_ACTION, PROCESSES_DECREMENT_ACTION: PROCESSES_DECREMENT_ACTION, PROCESSES_LOADER_RESET_ACTION: PROCESSES_LOADER_RESET_ACTION, processesIncrementMeta: processesIncrementMeta, processesDecrementMeta: processesDecrementMeta, processesLoaderResetMeta: processesLoaderResetMeta, ProcessesLoaderResetAction: ProcessesLoaderResetAction, ProcessesIncrementAction: ProcessesIncrementAction, ProcessesDecrementAction: ProcessesDecrementAction, isStableSelector: isStableSelector, hasPendingProcessesSelector: hasPendingProcessesSelector, initialProcessesState: initialProcessesState, processesLoaderReducer: processesLoaderReducer, serializeSearchConfig: serializeSearchConfig, denormalizeSearch: denormalizeSearch, denormalizeCustomB2BSearch: denormalizeCustomB2BSearch, normalizeListPage: normalizeListPage, serializeParams: serializeParams }); const ANONYMOUS_CONSENTS_STORE_FEATURE = 'anonymous-consents'; const ANONYMOUS_CONSENTS = '[Anonymous Consents] Anonymous Consents'; const LOAD_ANONYMOUS_CONSENT_TEMPLATES = '[Anonymous Consents] Load Anonymous Consent Templates'; const LOAD_ANONYMOUS_CONSENT_TEMPLATES_SUCCESS = '[Anonymous Consents] Load Anonymous Consent Templates Success'; const LOAD_ANONYMOUS_CONSENT_TEMPLATES_FAIL = '[Anonymous Consents] Load Anonymous Consent Templates Fail'; const RESET_LOAD_ANONYMOUS_CONSENT_TEMPLATES = '[Anonymous Consents] Reset Load Anonymous Consent Templates'; const GET_ALL_ANONYMOUS_CONSENTS = '[Anonymous Consents] Get All Anonymous Consents'; const GET_ANONYMOUS_CONSENT = '[Anonymous Consents] Get Anonymous Consent'; const SET_ANONYMOUS_CONSENTS = '[Anonymous Consents] Set Anonymous Consents'; const GIVE_ANONYMOUS_CONSENT = '[Anonymous Consents] Give Anonymous Consent'; const WITHDRAW_ANONYMOUS_CONSENT = '[Anonymous Consents] Withdraw Anonymous Consent'; const TOGGLE_ANONYMOUS_CONSENTS_BANNER_DISMISSED = '[Anonymous Consents] Toggle Anonymous Consents Banner Dismissed'; const TOGGLE_ANONYMOUS_CONSENT_TEMPLATES_UPDATED = '[Anonymous Consents] Anonymous Consent Templates Updated'; const ANONYMOUS_CONSENT_CHECK_UPDATED_VERSIONS = '[Anonymous Consents] Check Updated Versions'; class LoadAnonymousConsentTemplates extends LoaderLoadAction { constructor() { super(ANONYMOUS_CONSENTS); this.type = LOAD_ANONYMOUS_CONSENT_TEMPLATES; } } class LoadAnonymousConsentTemplatesSuccess extends LoaderSuccessAction { constructor(payload) { super(ANONYMOUS_CONSENTS); this.payload = payload; this.type = LOAD_ANONYMOUS_CONSENT_TEMPLATES_SUCCESS; } } class LoadAnonymousConsentTemplatesFail extends LoaderFailAction { constructor(payload) { super(ANONYMOUS_CONSENTS, payload); this.type = LOAD_ANONYMOUS_CONSENT_TEMPLATES_FAIL; } } class ResetLoadAnonymousConsentTemplates extends LoaderResetAction { constructor() { super(ANONYMOUS_CONSENTS); this.type = RESET_LOAD_ANONYMOUS_CONSENT_TEMPLATES; } } class GetAllAnonymousConsents { constructor() { this.type = GET_ALL_ANONYMOUS_CONSENTS; } } class GetAnonymousConsent { constructor(templateCode) { this.templateCode = templateCode; this.type = GET_ANONYMOUS_CONSENT; } } class SetAnonymousConsents { constructor(payload) { this.payload = payload; this.type = SET_ANONYMOUS_CONSENTS; } } class GiveAnonymousConsent { constructor(templateCode) { this.templateCode = templateCode; this.type = GIVE_ANONYMOUS_CONSENT; } } class WithdrawAnonymousConsent { constructor(templateCode) { this.templateCode = templateCode; this.type = WITHDRAW_ANONYMOUS_CONSENT; } } class ToggleAnonymousConsentsBannerDissmissed { constructor(dismissed) { this.dismissed = dismissed; this.type = TOGGLE_ANONYMOUS_CONSENTS_BANNER_DISMISSED; } } class ToggleAnonymousConsentTemplatesUpdated { constructor(updated) { this.updated = updated; this.type = TOGGLE_ANONYMOUS_CONSENT_TEMPLATES_UPDATED; } } class AnonymousConsentCheckUpdatedVersions { constructor() { this.type = ANONYMOUS_CONSENT_CHECK_UPDATED_VERSIONS; } } var anonymousConsentsGroup = /*#__PURE__*/Object.freeze({ __proto__: null, LOAD_ANONYMOUS_CONSENT_TEMPLATES: LOAD_ANONYMOUS_CONSENT_TEMPLATES, LOAD_ANONYMOUS_CONSENT_TEMPLATES_SUCCESS: LOAD_ANONYMOUS_CONSENT_TEMPLATES_SUCCESS, LOAD_ANONYMOUS_CONSENT_TEMPLATES_FAIL: LOAD_ANONYMOUS_CONSENT_TEMPLATES_FAIL, RESET_LOAD_ANONYMOUS_CONSENT_TEMPLATES: RESET_LOAD_ANONYMOUS_CONSENT_TEMPLATES, GET_ALL_ANONYMOUS_CONSENTS: GET_ALL_ANONYMOUS_CONSENTS, GET_ANONYMOUS_CONSENT: GET_ANONYMOUS_CONSENT, SET_ANONYMOUS_CONSENTS: SET_ANONYMOUS_CONSENTS, GIVE_ANONYMOUS_CONSENT: GIVE_ANONYMOUS_CONSENT, WITHDRAW_ANONYMOUS_CONSENT: WITHDRAW_ANONYMOUS_CONSENT, TOGGLE_ANONYMOUS_CONSENTS_BANNER_DISMISSED: TOGGLE_ANONYMOUS_CONSENTS_BANNER_DISMISSED, TOGGLE_ANONYMOUS_CONSENT_TEMPLATES_UPDATED: TOGGLE_ANONYMOUS_CONSENT_TEMPLATES_UPDATED, ANONYMOUS_CONSENT_CHECK_UPDATED_VERSIONS: ANONYMOUS_CONSENT_CHECK_UPDATED_VERSIONS, LoadAnonymousConsentTemplates: LoadAnonymousConsentTemplates, LoadAnonymousConsentTemplatesSuccess: LoadAnonymousConsentTemplatesSuccess, LoadAnonymousConsentTemplatesFail: LoadAnonymousConsentTemplatesFail, ResetLoadAnonymousConsentTemplates: ResetLoadAnonymousConsentTemplates, GetAllAnonymousConsents: GetAllAnonymousConsents, GetAnonymousConsent: GetAnonymousConsent, SetAnonymousConsents: SetAnonymousConsents, GiveAnonymousConsent: GiveAnonymousConsent, WithdrawAnonymousConsent: WithdrawAnonymousConsent, ToggleAnonymousConsentsBannerDissmissed: ToggleAnonymousConsentsBannerDissmissed, ToggleAnonymousConsentTemplatesUpdated: ToggleAnonymousConsentTemplatesUpdated, AnonymousConsentCheckUpdatedVersions: AnonymousConsentCheckUpdatedVersions }); const getAnonymousConsentState = createFeatureSelector(ANONYMOUS_CONSENTS_STORE_FEATURE); const getAnonymousConsentTemplatesState = createSelector(getAnonymousConsentState, (state) => state.templates); const getAnonymousConsentTemplatesValue = createSelector(getAnonymousConsentTemplatesState, loaderValueSelector); const getAnonymousConsentTemplatesLoading = createSelector(getAnonymousConsentTemplatesState, loaderLoadingSelector); const getAnonymousConsentTemplatesSuccess = createSelector(getAnonymousConsentTemplatesState, loaderSuccessSelector); const getAnonymousConsentTemplatesError = createSelector(getAnonymousConsentTemplatesState, loaderErrorSelector); const getAnonymousConsentTemplate = (templateCode) => { return createSelector(getAnonymousConsentTemplatesValue, (templates) => { return templates ? templates.find((template) => template.id === templateCode) : null; }); }; const getAnonymousConsentTemplatesUpdate = createSelector(getAnonymousConsentState, (state) => state.ui.updated); const getAnonymousConsentsBannerDismissed = createSelector(getAnonymousConsentState, (state) => state.ui.bannerDismissed); const getAnonymousConsents = createSelector(getAnonymousConsentState, (state) => state.consents); const getAnonymousConsentByTemplateCode = (templateCode) => createSelector(getAnonymousConsents, (consents) => consents.find((consent) => consent.templateCode === templateCode)); var anonymousConsentsGroup_selectors = /*#__PURE__*/Object.freeze({ __proto__: null, getAnonymousConsentTemplatesState: getAnonymousConsentTemplatesState, getAnonymousConsentTemplatesValue: getAnonymousConsentTemplatesValue, getAnonymousConsentTemplatesLoading: getAnonymousConsentTemplatesLoading, getAnonymousConsentTemplatesSuccess: getAnonymousConsentTemplatesSuccess, getAnonymousConsentTemplatesError: getAnonymousConsentTemplatesError, getAnonymousConsentTemplate: getAnonymousConsentTemplate, getAnonymousConsentTemplatesUpdate: getAnonymousConsentTemplatesUpdate, getAnonymousConsentsBannerDismissed: getAnonymousConsentsBannerDismissed, getAnonymousConsents: getAnonymousConsents, getAnonymousConsentByTemplateCode: getAnonymousConsentByTemplateCode, getAnonymousConsentState: getAnonymousConsentState }); const OCC_USER_ID_CURRENT = 'current'; const OCC_USER_ID_ANONYMOUS = 'anonymous'; const OCC_USER_ID_GUEST = 'guest'; const OCC_CART_ID_CURRENT = 'current'; const LOGIN = '[Auth] Login'; const LOGOUT = '[Auth] Logout'; class Login { constructor() { this.type = LOGIN; } } class Logout { constructor() { this.type = LOGOUT; } } var authGroup_actions = /*#__PURE__*/Object.freeze({ __proto__: null, LOGIN: LOGIN, LOGOUT: LOGOUT, Login: Login, Logout: Logout }); /** * This implementation is OCC specific. * Different backend might have completely different need regarding user id. * It might not need user id at all and work based on access_token. * To implement custom solution provide your own implementation and customize services that use UserIdService */ class UserIdService { constructor() { this._userId = new ReplaySubject(1); } /** * Sets current user id. * * @param userId */ setUserId(userId) { this._userId.next(userId); } /** * This function provides the userId the OCC calls should use, depending * on whether there is an active storefront session or not. * * It returns the userId of the current storefront user or 'anonymous' * in the case there are no signed in user in the storefront. * * The user id of a regular customer session is 'current'. In the case of an * asm customer emulation session, the userId will be the customerId. */ getUserId() { return this._userId; } /** * Utility method if you need userId to perform single action (eg. dispatch call to API). * * @param loggedIn Set to true if you want the observable to emit id only for logged in user. Throws in case of anonymous user. * * @returns Observable that emits once and completes with the last userId value. */ takeUserId(loggedIn = false) { return this.getUserId().pipe(take(1), map((userId) => { if (loggedIn && userId === OCC_USER_ID_ANONYMOUS) { throw new Error('Requested user id for logged user while user is not logged in.'); } return userId; })); } /** * Sets user id to the default value for logged out user. */ clearUserId() { this.setUserId(OCC_USER_ID_ANONYMOUS); } /** * Checks if the userId is of emulated user type. */ isEmulated() { return this.getUserId().pipe(map((userId) => userId !== OCC_USER_ID_ANONYMOUS && userId !== OCC_USER_ID_CURRENT)); } } UserIdService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.0.5", ngImport: i0, type: UserIdService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); UserIdService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "12.0.5", ngImport: i0, type: UserIdService, providedIn: 'root' }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.0.5", ngImport: i0, type: UserIdService, decorators: [{ type: Injectable, args: [{ providedIn: 'root', }] }] }); /** * Supported OAuth flows. */ var OAuthFlow; (function (OAuthFlow) { /** * Flow when username and password is passed to the application and then the application through API fetches tokens from OAuth server. */ OAuthFlow[OAuthFlow["ResourceOwnerPasswordFlow"] = 0] = "ResourceOwnerPasswordFlow"; /** * Flow with redirect to OAuth server where user inputs credentials and the are redirected back with token. */ OAuthFlow[OAuthFlow["ImplicitFlow"] = 1] = "ImplicitFlow"; /** * Similar to Implicit flow, but user is redirected with code that need to later exchange through API for a token. */ OAuthFlow[OAuthFlow["AuthorizationCode"] = 2] = "AuthorizationCode"; })(OAuthFlow || (OAuthFlow = {})); class AuthConfig { } AuthConfig.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.0.5", ngImport: i0, type: AuthConfig, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); AuthConfig.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "12.0.5", ngImport: i0, type: AuthConfig, providedIn: 'root', useExisting: Config }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.0.5", ngImport: i0, type: AuthConfig, decorators: [{ type: Injectable, args: [{ providedIn: 'root', useExisting: Config, }] }] }); class SiteContextConfig { } SiteContextConfig.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.0.5", ngImport: i0, type: SiteContextConfig, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); SiteContextConfig.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "12.0.5", ngImport: i0, type: SiteContextConfig, providedIn: 'root', useExisting: Config }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.0.5", ngImport: i0, type: SiteContextConfig, decorators: [{ type: Injectable, args: [{ providedIn: 'root', useExisting: Config, }] }] }); class OccConfig extends SiteContextConfig { } OccConfig.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.0.5", ngImport: i0, type: OccConfig, deps: null, target: i0.ɵɵFactoryTarget.Injectable }); OccConfig.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "12.0.5", ngImport: i0, type: OccConfig, providedIn: 'root', useExisting: Config }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.0.5", ngImport: i0, type: OccConfig, decorators: [{ type: Injectable, args: [{ providedIn: 'root', useExisting: Config, }] }] }); /** * Utility service on top of the authorization config. * Provides handy defaults, when not everything is set in the configuration. * Use this service instead of direct configuration. */ class AuthConfigService { constructor(authConfig, occConfig) { this.authConfig = authConfig; this.occConfig = occConfig; } /** * Utility to make access to authentication config easier. */ get config() { var _a, _b; return (_b = (_a = this.authConfig) === null || _a === void 0 ? void 0 : _a.authentication) !== null && _b !== void 0 ? _b : {}; } /** * Get client_id * * @return client_id */ getClientId() { var _a; return (_a = this.config.client_id) !== null && _a !== void 0 ? _a : ''; } /** * Get client_secret. OAuth server shouldn't require it from web apps (but Hybris OAuth server requires). * * @return client_secret */ getClientSecret() { var _a; return (_a = this.config.client_secret) !== null && _a !== void 0 ? _a : ''; } /** * Returns base url of the authorization server */ getBaseUrl() { var _a, _b, _c, _d, _e; return ((_a = this.config.baseUrl) !== null && _a !== void 0 ? _a : ((_e = (_d = (_c = (_b = this.occConfig) === null || _b === void 0 ? void 0 : _b.backend) === null || _c === void 0 ? void 0 : _c.occ) === null || _d === void 0 ? void 0 : _d.baseUrl) !== null && _e !== void 0 ? _e : '') + '/authorizationserver'); } /** * Returns endpoint for getting the auth token */ getTokenEndpoint() { var _a; const tokenEndpoint = (_a = this.config.tokenEndpoint) !== null && _a !== void 0 ? _a : ''; return this.prefixEndpoint(tokenEndpoint); } /** * Returns url for redirect to the authorization server to get token/code */ getLoginUrl() { var _a; const loginUrl = (_a = this.config.loginUrl) !== null && _a !== void 0 ? _a : ''; return this.prefixEndpoint(loginUrl); } /** * Returns endpoint for token revocation (both access and refresh token). */ getRevokeEndpoint() { var _a; const revokeEndpoint = (_a = this.config.revokeEndpoint) !== null && _a !== void 0 ? _a : ''; return this.prefixEndpoint(revokeEndpoint); } /** * Returns logout url to redirect to on logout. */ getLogoutUrl() { var _a; const logoutUrl = (_a = this.config.logoutUrl) !== null && _a !== void 0 ? _a : ''; return this.prefixEndpoint(logoutUrl); } /** * Returns userinfo endpoint of the OAuth server. */ getUserinfoEndpoint() { var _a; const userinfoEndpoint = (_a = this.config.userinfoEndpoint) !== null && _a !== void 0 ? _a : ''; return this.prefixEndpoint(userinfoEndpoint); } /** * Returns configuration specific for the angular-oauth2-oidc library. */ getOAuthLibConfig() { var _a; return (_a = this.config.OAuthLibConfig) !== null && _a !== void 0 ? _a : {}; } prefixEndpoint(endpoint) { let url = endpoint; if (!url.startsWith('/')) { url = '/' + url; } return