From 8ff7e3528b7b614e51559bb287f37190d33ead63 Mon Sep 17 00:00:00 2001 From: christophercr Date: Wed, 20 Jun 2018 13:02:46 +0200 Subject: [PATCH] feat(stark-build): add support for environment variables at runtime (importing environment.ts file) and at compilation time (using webpack Define plugin) ISSUES CLOSED: #50 --- package.json | 2 +- packages/stark-build/config/build-utils.js | 45 +++++------------- packages/stark-build/config/ng-cli-utils.js | 27 +++++++++-- packages/stark-build/config/webpack.common.js | 47 ++++++++++--------- packages/stark-build/config/webpack.dev.js | 8 ++-- packages/stark-build/config/webpack.prod.js | 11 ++--- packages/stark-build/package.json | 1 + packages/stark-build/tsconfig.json | 2 +- .../typings/environment/index.d.ts | 3 ++ packages/stark-build/typings/index.d.ts | 3 ++ packages/stark-core/src/common.ts | 1 + packages/stark-core/src/common/environment.ts | 31 ++++++++++++ .../entities/application/app-config.entity.ts | 11 +++-- .../http/builder/http-request-builder.ts | 16 +++---- .../src/modules/http/services/http.service.ts | 8 ++-- .../src/modules/http/testing/http.mock.ts | 8 +++- .../modules/logging/testing/logging.mock.ts | 2 +- .../modules/routing/testing/routing.mock.ts | 2 +- .../session/services/session.service.ts | 30 ++++++------ .../modules/session/testing/session.mock.ts | 3 +- .../src/modules/user/services/user.service.ts | 13 ++--- .../stark-core/testing/tsconfig-build.json | 10 +++- packages/stark-core/tsconfig-build.json | 7 ++- packages/tsconfig.json | 2 + showcase/package.json | 15 +++--- showcase/src/custom-typings.d.ts | 36 +------------- .../src/environments/environment.e2e.prod.ts | 4 +- showcase/src/environments/environment.hmr.ts | 5 +- showcase/src/environments/environment.prod.ts | 4 +- showcase/src/environments/environment.ts | 6 ++- showcase/src/environments/model.ts | 8 ---- showcase/src/index.html | 12 +++++ showcase/tsconfig.json | 2 +- starter/package.json | 13 ++--- starter/src/custom-typings.d.ts | 36 +------------- .../src/environments/environment.e2e.prod.ts | 4 +- starter/src/environments/environment.hmr.ts | 4 +- starter/src/environments/environment.prod.ts | 5 +- starter/src/environments/environment.ts | 4 +- starter/src/environments/model.ts | 23 --------- starter/tsconfig.json | 2 +- 41 files changed, 229 insertions(+), 247 deletions(-) create mode 100644 packages/stark-build/typings/environment/index.d.ts create mode 100644 packages/stark-build/typings/index.d.ts create mode 100644 packages/stark-core/src/common/environment.ts delete mode 100644 showcase/src/environments/model.ts diff --git a/package.json b/package.json index 747122b61d..a9b9b6369b 100644 --- a/package.json +++ b/package.json @@ -152,7 +152,7 @@ "update:starter": "npm run clean:starter && npm run install:starter" }, "lint-staged": { - "*.{css,js,json,pcss,scss,ts}": [ + "*.{css,js,json,md,pcss,scss,ts}": [ "prettier --write", "git add" ] diff --git a/packages/stark-build/config/build-utils.js b/packages/stark-build/config/build-utils.js index dfca931cd1..7c26e58a73 100644 --- a/packages/stark-build/config/build-utils.js +++ b/packages/stark-build/config/build-utils.js @@ -4,24 +4,24 @@ const fs = require("fs"); const helpers = require("./helpers"); const ngCliUtils = require("./ng-cli-utils"); -const _getAngularCliAppConfig = getAngularCliAppConfig(); +const angularCliAppConfig = ngCliUtils.getAngularCliAppConfig(helpers.root("angular.json")); const ANGULAR_APP_CONFIG = { - config: _getAngularCliAppConfig, - deployUrl: _getAngularCliAppConfig.architect.build.options.deployUrl || "", - baseHref: _getAngularCliAppConfig.architect.build.options.baseHref || "/", - sourceRoot: _getAngularCliAppConfig.sourceRoot, - outputPath: _getAngularCliAppConfig.architect.build.options.outputPath + config: angularCliAppConfig, + deployUrl: angularCliAppConfig.architect.build.options.deployUrl || "", + baseHref: angularCliAppConfig.architect.build.options.baseHref || "/", + sourceRoot: angularCliAppConfig.sourceRoot, + outputPath: angularCliAppConfig.architect.build.options.outputPath }; const DEFAULT_METADATA = { - title: "Stark Application by @NationalBankBelgium", - baseUrl: "/", - isDevServer: helpers.isWebpackDevServer(), + TITLE: "Stark Application by @NationalBankBelgium", + BASE_URL: "/", + IS_DEV_SERVER: helpers.isWebpackDevServer(), HMR: helpers.hasProcessFlag("hot"), AOT: process.env.BUILD_AOT || helpers.hasNpmFlag("aot"), E2E: !!process.env.BUILD_E2E, WATCH: helpers.hasProcessFlag("watch"), - tsConfigPath: ANGULAR_APP_CONFIG.config.architect.build.options.tsConfig, + TS_CONFIG_PATH: ANGULAR_APP_CONFIG.config.architect.build.options.tsConfig, environment: "" }; @@ -76,11 +76,11 @@ function getEnvironmentFile(environment) { * Read the tsconfig to determine if we should prefer ES2015 modules. * Load rxjs path aliases. * https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md#build-and-treeshaking - * @param supportES2015 Set to true when the output of typescript is >= ES6 + * @param shouldSupportES2015 Set to true when the output of typescript is >= ES6 */ -function rxjsAlias(supportES2015) { +function rxjsAlias(shouldSupportES2015) { try { - const rxjsPathMappingImport = supportES2015 ? "rxjs/_esm2015/path-mapping" : "rxjs/_esm5/path-mapping"; + const rxjsPathMappingImport = shouldSupportES2015 ? "rxjs/_esm2015/path-mapping" : "rxjs/_esm5/path-mapping"; const rxPaths = require(rxjsPathMappingImport); return rxPaths(); } catch (e) { @@ -143,25 +143,6 @@ function getApplicationAssetsConfig() { return []; } -function getAngularCliAppConfig() { - const applicationAngularCliConfigPath = helpers.root("angular.json"); - if (fs.existsSync(applicationAngularCliConfigPath)) { - const angularCliConfig = require(applicationAngularCliConfigPath); - const cliConfig = ngCliUtils.validateAngularCLIConfig(angularCliConfig); - if (cliConfig) { - if (cliConfig.defaultProject && cliConfig.projects[cliConfig.defaultProject]) { - return cliConfig.projects[cliConfig.defaultProject]; - } else { - throw new Error("Angular-cli config apps is wrong. Please adapt it to follow Angular CLI way."); - } - } else { - throw new Error("Parsing " + applicationAngularCliConfigPath + " failed. Ensure the file is valid JSON."); - } - } else { - throw new Error("angular.json is not present. Please add this at the root your project because stark-build needs this."); - } -} - /** * Return copyWebpack config based on angular cli assets declaration * diff --git a/packages/stark-build/config/ng-cli-utils.js b/packages/stark-build/config/ng-cli-utils.js index 970ae34ae8..aee3385e1a 100644 --- a/packages/stark-build/config/ng-cli-utils.js +++ b/packages/stark-build/config/ng-cli-utils.js @@ -3,9 +3,9 @@ const fs = require("fs"); const cliUtilConfig = require("@angular/cli/utilities/config"); const { formatDiagnostics } = require("@angular/compiler-cli/ngtools2"); -function isDirectory(path) { +function isDirectory(pathToCheck) { try { - return fs.statSync(path).isDirectory(); + return fs.statSync(pathToCheck).isDirectory(); } catch (_) { return false; } @@ -15,6 +15,26 @@ function getDirectoriesNames(source) { return fs.readdirSync(source).filter(name => isDirectory(path.join(source, name))); } +function getAngularCliAppConfig(angularCliAppConfigPath) { + if (fs.existsSync(angularCliAppConfigPath)) { + const angularCliConfig = require(angularCliAppConfigPath); + const cliConfig = validateAngularCLIConfig(angularCliConfig); + if (cliConfig) { + if (cliConfig.defaultProject && cliConfig.projects[cliConfig.defaultProject]) { + return cliConfig.projects[cliConfig.defaultProject]; + } else { + throw new Error( + "The configuration of the default project in angular.json is wrong. Please adapt it to follow Angular CLI guidelines." + ); + } + } else { + throw new Error("Parsing " + angularCliAppConfigPath + " failed. Please make sure that the file is valid JSON."); + } + } else { + throw new Error("angular.json is not present. Please add this at the root your project because stark-build needs this."); + } +} + /** * Validate passed angular cli config based on schema: @angular/cli/lib/config/schema.json * If the serialized file is equal to the passed json, return the serialized config. @@ -43,7 +63,8 @@ function getWorkspace() { return cliUtilConfig.getWorkspace(); } +exports.getAngularCliAppConfig = getAngularCliAppConfig; exports.getDirectoriesNames = getDirectoriesNames; +exports.getWorkspace = getWorkspace; exports.isDirectory = isDirectory; exports.validateAngularCLIConfig = validateAngularCLIConfig; -exports.getWorkspace = getWorkspace; diff --git a/packages/stark-build/config/webpack.common.js b/packages/stark-build/config/webpack.common.js index 37ee203b6f..6057614132 100644 --- a/packages/stark-build/config/webpack.common.js +++ b/packages/stark-build/config/webpack.common.js @@ -12,6 +12,7 @@ const commonData = require("./webpack.common-data.js"); // common configuration const CopyWebpackPlugin = require("copy-webpack-plugin"); const HtmlWebpackPlugin = require("html-webpack-plugin"); const BaseHrefWebpackPlugin = require("base-href-webpack-plugin").BaseHrefWebpackPlugin; +const DefinePlugin = require("webpack/lib/DefinePlugin"); // const InlineManifestWebpackPlugin = require("inline-manifest-webpack-plugin"); // const ScriptExtHtmlWebpackPlugin = require("script-ext-html-webpack-plugin"); const { AngularCompilerPlugin } = require("@ngtools/webpack"); @@ -30,14 +31,14 @@ const buildUtils = require("./build-utils"); module.exports = options => { const isProd = options.ENV === "production"; const METADATA = Object.assign({}, buildUtils.DEFAULT_METADATA, options.metadata || {}); - const supportES2015 = buildUtils.supportES2015(METADATA.tsConfigPath); + const supportES2015 = buildUtils.supportES2015(METADATA.TS_CONFIG_PATH); const entry = { polyfills: "./src/polyfills.browser.ts", main: "./src/main.browser.ts" }; - const tsConfigApp = buildUtils.readTsConfig(helpers.root(METADATA.tsConfigPath)); + const tsConfigApp = buildUtils.readTsConfig(helpers.root(METADATA.TS_CONFIG_PATH)); const defaultNgcOptions = { generateCodeForLibraries: true, @@ -342,24 +343,26 @@ module.exports = options => { * See: http://webpack.github.io/docs/configuration.html#plugins */ plugins: [ - // /** - // * Plugin: DefinePlugin - // * Description: Define free variables. - // * Useful for having development builds with debug logging or adding global constants. - // * - // * Environment helpers - // * - // * See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin - // */ - // // NOTE: when adding more properties make sure you include them in custom-typings.d.ts - // new DefinePlugin({ - // 'ENV': JSON.stringify(METADATA.ENV), - // 'HMR': METADATA.HMR, - // 'AOT': METADATA.AOT, - // 'process.env.ENV': JSON.stringify(METADATA.ENV), - // 'process.env.NODE_ENV': JSON.stringify(METADATA.ENV), - // 'process.env.HMR': METADATA.HMR - // }), + /** + * Plugin: DefinePlugin + * Description: Define free variables. + * Useful for having development builds with debug logging or adding global constants. + * + * Environment helpers + * IMPORTANT: when adding more properties make sure you include them in typings/environment.d.ts + * + * See: https://webpack.js.org/plugins/define-plugin + */ + new DefinePlugin({ + ENV: JSON.stringify(METADATA.ENV), + HMR: METADATA.HMR, + AOT: METADATA.AOT, // TODO: is this needed? + "process.env": { + ENV: JSON.stringify(METADATA.ENV), + NODE_ENV: JSON.stringify(METADATA.ENV), + HMR: METADATA.HMR + } + }), /** * Plugin: AngularNamedLazyChunksWebpackPlugin @@ -441,7 +444,7 @@ module.exports = options => { */ new HtmlWebpackPlugin({ template: "src/index.html", - title: METADATA.title, + title: METADATA.TITLE, chunksSortMode: function(a, b) { const entryPoints = ["inline", "polyfills", "sw-register", "styles", "vendor", "main"]; return entryPoints.indexOf(a.names[0]) - entryPoints.indexOf(b.names[0]); @@ -493,7 +496,7 @@ module.exports = options => { }, platform: 0, // 0 = browser, 1 = server compilerOptions: appNgcOptions, - tsConfigPath: METADATA.tsConfigPath + tsConfigPath: METADATA.TS_CONFIG_PATH }) /** diff --git a/packages/stark-build/config/webpack.dev.js b/packages/stark-build/config/webpack.dev.js index 44dc005c76..4ab445c7ef 100644 --- a/packages/stark-build/config/webpack.dev.js +++ b/packages/stark-build/config/webpack.dev.js @@ -25,18 +25,16 @@ const WebpackMonitor = require("webpack-monitor"); * See: https://webpack.js.org/configuration/ */ module.exports = function(env) { - // for the content of the env parameter see here : https://webpack.js.org/api/cli/#environment-options const ENV = (process.env.ENV = process.env.NODE_ENV = "development"); - const HOST = process.env.HOST || "localhost"; - const PORT = process.env.PORT || 3000; let MONITOR = false; + // for the content of the env parameter see here : https://webpack.js.org/api/cli/#environment-options if (env && typeof env.monitor !== "undefined") { MONITOR = env.monitor; } const METADATA = Object.assign({}, buildUtils.DEFAULT_METADATA, { - HOST: HOST, - PORT: PORT, + HOST: process.env.HOST || "localhost", + PORT: process.env.PORT || 3000, ENV: ENV, HMR: helpers.hasProcessFlag("hot"), environment: helpers.hasProcessFlag("hot") ? "hmr" : "dev" diff --git a/packages/stark-build/config/webpack.prod.js b/packages/stark-build/config/webpack.prod.js index bc476e7bd6..ba6205a258 100644 --- a/packages/stark-build/config/webpack.prod.js +++ b/packages/stark-build/config/webpack.prod.js @@ -47,15 +47,14 @@ function getUglifyOptions(supportES2015) { module.exports = function() { const ENV = (process.env.NODE_ENV = process.env.ENV = "production"); - const supportES2015 = buildUtils.supportES2015(buildUtils.DEFAULT_METADATA.tsConfigPath); const METADATA = Object.assign({}, buildUtils.DEFAULT_METADATA, { - host: process.env.HOST || "localhost", - port: process.env.PORT || 8080, + HOST: process.env.HOST || "localhost", + PORT: process.env.PORT || 8080, ENV: ENV, - HMR: false + HMR: false, + environment: buildUtils.DEFAULT_METADATA.E2E ? "e2e.prod" : "prod" }); - - METADATA.environment = METADATA.E2E ? "e2e.prod" : "prod"; + const supportES2015 = buildUtils.supportES2015(METADATA.TS_CONFIG_PATH); return webpackMerge(commonConfig({ ENV: ENV, metadata: METADATA }), { /** diff --git a/packages/stark-build/package.json b/packages/stark-build/package.json index 90bb915076..d4ac447d6d 100644 --- a/packages/stark-build/package.json +++ b/packages/stark-build/package.json @@ -17,6 +17,7 @@ "node": ">=6.11.0", "npm": ">=5.3.0" }, + "types": "typings/index.d.ts", "dependencies": { "@angular-devkit/build-angular": "0.6.8", "@angular-devkit/build-optimizer": "0.6.8", diff --git a/packages/stark-build/tsconfig.json b/packages/stark-build/tsconfig.json index ca67f11dcf..9b0051a4c7 100644 --- a/packages/stark-build/tsconfig.json +++ b/packages/stark-build/tsconfig.json @@ -42,7 +42,7 @@ "target": "es5", "outDir": "./dist", "baseUrl": "./src", - "rootDirs": ["./src", "./config"], + "rootDirs": ["./src", "./config", "./typings"], "lib": ["dom", "dom.iterable", "es2017"], "typeRoots": ["./node_modules/@types"], "paths": {}, diff --git a/packages/stark-build/typings/environment/index.d.ts b/packages/stark-build/typings/environment/index.d.ts new file mode 100644 index 0000000000..9a283bd575 --- /dev/null +++ b/packages/stark-build/typings/environment/index.d.ts @@ -0,0 +1,3 @@ +// Extra variables that live on Global that will be replaced by webpack DefinePlugin +declare let ENV: "development" | "production"; +declare let HMR: boolean; diff --git a/packages/stark-build/typings/index.d.ts b/packages/stark-build/typings/index.d.ts new file mode 100644 index 0000000000..653ee24d58 --- /dev/null +++ b/packages/stark-build/typings/index.d.ts @@ -0,0 +1,3 @@ +/* tslint:disable:no-import-side-effect */ +import "./environment"; +/* tslint:enable */ diff --git a/packages/stark-core/src/common.ts b/packages/stark-core/src/common.ts index 29ab023db4..d70bd92b54 100644 --- a/packages/stark-core/src/common.ts +++ b/packages/stark-core/src/common.ts @@ -1,3 +1,4 @@ +export * from "./common/environment"; export * from "./common/error"; export * from "./common/routes"; export * from "./common/store"; diff --git a/packages/stark-core/src/common/environment.ts b/packages/stark-core/src/common/environment.ts new file mode 100644 index 0000000000..82d0fde1bd --- /dev/null +++ b/packages/stark-core/src/common/environment.ts @@ -0,0 +1,31 @@ +import { NgModuleRef } from "@angular/core"; + +/** + * Interface to be implemented by all environments + */ +export interface StarkEnvironment { + /** + * Whether the current environment is production + */ + production: boolean; + /** + * Whether the current environment has Hot Module Replacement enabled + */ + hmr: boolean; + /** + * Array of providers to be included in this environment + */ + ENV_PROVIDERS: any[]; + /** + * Function to modify/decorate the NgModule Instance created by Angular for a given platform. + * Useful to enable/disable some Angular specifics such as the debug tools. + */ + decorateModuleRef(modRef: NgModuleRef): NgModuleRef; +} + +// create an empty dummy environment constant (the actual values will be defined in the client app) +const dummyEnv: Partial = {}; + +// export the dummy constant as "environment" to be able to mimic the way it should be imported in the client app +// like this: import { environment } from "environments/environment"; +export const environment: StarkEnvironment = dummyEnv; diff --git a/packages/stark-core/src/configuration/entities/application/app-config.entity.ts b/packages/stark-core/src/configuration/entities/application/app-config.entity.ts index 01b7dff500..797d17c040 100644 --- a/packages/stark-core/src/configuration/entities/application/app-config.entity.ts +++ b/packages/stark-core/src/configuration/entities/application/app-config.entity.ts @@ -124,12 +124,13 @@ export class StarkApplicationConfigImpl implements StarkApplicationConfig { public constructor() { // Default values - // FIXME: DEVELOPMENT env variable? - /*if (DEVELOPMENT) { + if (ENV === "development") { this.loggingFlushPersistSize = 500; - } else {*/ - this.loggingFlushPersistSize = 15; - // } + console.log("CCR==========> this line should be kept only in DEV"); + } else { + this.loggingFlushPersistSize = 15; + console.log("CCR==========> this line should be kept only in PROD"); + } this.loggingFlushDisabled = false; this.loggingFlushResourceName = "logging"; diff --git a/packages/stark-core/src/modules/http/builder/http-request-builder.ts b/packages/stark-core/src/modules/http/builder/http-request-builder.ts index e47bfd1899..4b73dffd3e 100644 --- a/packages/stark-core/src/modules/http/builder/http-request-builder.ts +++ b/packages/stark-core/src/modules/http/builder/http-request-builder.ts @@ -162,10 +162,10 @@ export class StarkHttpRequestBuilderImpl implements Sta // Add custom QueryParameter so json-server can add collection metadata to the mock response // See: https://jira.prd.nbb/browse/NG-1335 - // FIXME: DEVELOPMENT env variable? - // if (DEVELOPMENT) { - builder.addQueryParameter("mockCollectionRequest", "true"); - // } + if (ENV === "development") { + builder.addQueryParameter("mockCollectionRequest", "true"); + console.log("CCR==========> this line should be kept only in DEV"); + } return builder; } @@ -200,10 +200,10 @@ export class StarkHttpRequestBuilderImpl implements Sta // Add custom QueryParameter so json-server can add collection metadata to the mock response // See: https://jira.prd.nbb/browse/NG-1335 - // FIXME: DEVELOPMENT env variable? - // if (DEVELOPMENT) { - builder.addQueryParameter("mockCollectionRequest", "true"); - // } + if (ENV === "development") { + builder.addQueryParameter("mockCollectionRequest", "true"); + console.log("CCR==========> this line should be kept only in DEV"); + } return builder; } diff --git a/packages/stark-core/src/modules/http/services/http.service.ts b/packages/stark-core/src/modules/http/services/http.service.ts index 0e2b968eec..fdbb322dd6 100644 --- a/packages/stark-core/src/modules/http/services/http.service.ts +++ b/packages/stark-core/src/modules/http/services/http.service.ts @@ -51,9 +51,9 @@ export class StarkHttpServiceImpl

implements StarkHttpS request = this.removeETagFromRequestItem(request); // NG-1346: fake pre-authentication support - // FIXME: DEVELOPMENT env variable? - if (/*DEVELOPMENT &&*/ request.backend.fakePreAuthenticationEnabled) { + if (ENV === "development" && request.backend.fakePreAuthenticationEnabled) { request = this.addFakePreAuthenticationHeaders(request); + console.log("CCR==========> this line should be kept only in DEV"); } // NG-117: add correlation identifier @@ -97,9 +97,9 @@ export class StarkHttpServiceImpl

implements StarkHttpS public executeCollectionRequest(request: StarkHttpRequest

): Observable> { // NG-1346: fake pre-authentication support - // FIXME: DEVELOPMENT env variable? - if (/*DEVELOPMENT &&*/ request.backend.fakePreAuthenticationEnabled) { + if (ENV === "development" && request.backend.fakePreAuthenticationEnabled) { request = this.addFakePreAuthenticationHeaders(request); + console.log("CCR==========> this line should be kept only in DEV"); } // NG-117: add correlation identifier diff --git a/packages/stark-core/src/modules/http/testing/http.mock.ts b/packages/stark-core/src/modules/http/testing/http.mock.ts index 341ad11322..28886c4edf 100644 --- a/packages/stark-core/src/modules/http/testing/http.mock.ts +++ b/packages/stark-core/src/modules/http/testing/http.mock.ts @@ -1,5 +1,9 @@ -import { StarkHttpService } from "../services"; -import { StarkHttpRequest, StarkSingleItemResponseWrapper, StarkCollectionResponseWrapper } from "../entities"; +import { + StarkHttpService, + StarkHttpRequest, + StarkSingleItemResponseWrapper, + StarkCollectionResponseWrapper +} from "@nationalbankbelgium/stark-core"; import { HttpClient } from "@angular/common/http"; import { Observable } from "rxjs"; /** diff --git a/packages/stark-core/src/modules/logging/testing/logging.mock.ts b/packages/stark-core/src/modules/logging/testing/logging.mock.ts index 47724fc001..8cef34c071 100644 --- a/packages/stark-core/src/modules/logging/testing/logging.mock.ts +++ b/packages/stark-core/src/modules/logging/testing/logging.mock.ts @@ -1,4 +1,4 @@ -import { StarkLoggingService } from "../services"; +import { StarkLoggingService } from "@nationalbankbelgium/stark-core"; /** * Mock class of the StarkLoggingService interface. diff --git a/packages/stark-core/src/modules/routing/testing/routing.mock.ts b/packages/stark-core/src/modules/routing/testing/routing.mock.ts index 66ac2c9b91..cc9d8a0d21 100644 --- a/packages/stark-core/src/modules/routing/testing/routing.mock.ts +++ b/packages/stark-core/src/modules/routing/testing/routing.mock.ts @@ -1,4 +1,4 @@ -import { StarkRoutingService, StarkStateConfigWithParams } from "../services"; +import { StarkRoutingService, StarkStateConfigWithParams } from "@nationalbankbelgium/stark-core"; import { Observable } from "rxjs"; import { HookFn, HookMatchCriteria, HookRegOptions, RawParams, StateDeclaration, StateObject, TransitionOptions } from "@uirouter/core"; /** diff --git a/packages/stark-core/src/modules/session/services/session.service.ts b/packages/stark-core/src/modules/session/services/session.service.ts index a9a1928422..409dc69d5d 100644 --- a/packages/stark-core/src/modules/session/services/session.service.ts +++ b/packages/stark-core/src/modules/session/services/session.service.ts @@ -8,7 +8,7 @@ import { select, Store } from "@ngrx/store"; import { StateObject } from "@uirouter/core"; import { validateSync } from "class-validator"; import { defer, Observable, Subject } from "rxjs"; -import { map, take } from "rxjs/operators"; +import { map, take, filter, tap } from "rxjs/operators"; import { STARK_LOGGING_SERVICE, StarkLoggingService } from "../../logging/services"; import { StarkSessionService, starkSessionServiceName } from "./session.service.intf"; @@ -89,13 +89,15 @@ export class StarkSessionServiceImpl implements StarkSessionService { this.session$ = this.store.pipe(select(selectStarkSession)); - // FIXME Where does DEVELOPMENT Variable come from ??? - // if (DEVELOPMENT) { - // this.session$.pipe( - // filter((session: StarkSession) => session.hasOwnProperty("user")), - // tap((session: StarkSession) => this.setFakePreAuthenticationHeaders(session.user)) - // ).subscribe(); - // } + if (ENV === "development") { + this.session$ + .pipe( + filter((session: StarkSession) => session.hasOwnProperty("user")), + tap((session: StarkSession) => this.setFakePreAuthenticationHeaders(session.user)) + ) + .subscribe(); + console.log("CCR==========> this line should be kept only in DEV"); + } if (window) { window.addEventListener("beforeunload", () => { @@ -292,12 +294,12 @@ export class StarkSessionServiceImpl implements StarkSessionService { let pingRequestHeaders: HttpHeaders = new HttpHeaders(); pingRequestHeaders = pingRequestHeaders.set(StarkHttpHeaders.NBB_CORRELATION_ID, this.logger.correlationId); - // FIXME Where does DEVELOPMENT Variable come from ??? - // if (DEVELOPMENT) { - this.fakePreAuthenticationHeaders.forEach((value: string, key: string) => { - pingRequestHeaders = pingRequestHeaders.set(key, value); - }); - // } + if (ENV === "development") { + this.fakePreAuthenticationHeaders.forEach((value: string, key: string) => { + pingRequestHeaders = pingRequestHeaders.set(key, value); + }); + console.log("CCR==========> this line should be kept only in DEV"); + } const pingRequest: HttpRequest = new HttpRequest("GET", this.appConfig.keepAliveUrl, { headers: pingRequestHeaders diff --git a/packages/stark-core/src/modules/session/testing/session.mock.ts b/packages/stark-core/src/modules/session/testing/session.mock.ts index 1a26d27705..d020e7065d 100644 --- a/packages/stark-core/src/modules/session/testing/session.mock.ts +++ b/packages/stark-core/src/modules/session/testing/session.mock.ts @@ -1,5 +1,4 @@ -import { StarkHttpHeaders } from "../../http/constants"; -import { StarkSessionService } from "../services"; +import { StarkHttpHeaders, StarkSessionService } from "@nationalbankbelgium/stark-core"; import { Observable } from "rxjs"; /** * @ignore diff --git a/packages/stark-core/src/modules/user/services/user.service.ts b/packages/stark-core/src/modules/user/services/user.service.ts index a299750d96..bd72713909 100644 --- a/packages/stark-core/src/modules/user/services/user.service.ts +++ b/packages/stark-core/src/modules/user/services/user.service.ts @@ -2,6 +2,7 @@ import { Inject, Injectable } from "@angular/core"; import { Store } from "@ngrx/store"; import { validateSync } from "class-validator"; +import { Deserialize } from "cerialize"; import { Observable, throwError } from "rxjs"; import { catchError, map } from "rxjs/operators"; @@ -42,16 +43,16 @@ export class StarkUserServiceImpl implements StarkUserService { @Inject(STARK_LOGGING_SERVICE) public logger: StarkLoggingService, @Inject(STARK_USER_REPOSITORY) public userRepository: StarkUserRepository, // FIXME Use starkMockData - @Inject(STARK_MOCK_DATA) _starkMockData: StarkMockData, + @Inject(STARK_MOCK_DATA) starkMockData: StarkMockData, public store: Store ) { this.logger.debug(starkUserServiceName + " loaded"); - // FIXME Where does DEVELOPMENT Variable come from ??? - // if (DEVELOPMENT) { - // this.logger.debug(starkUserServiceName + ": Retrieving the user profiles from the mock data"); - // this.userProfiles = Deserialize(starkMockData.profiles, StarkUser); - // } + if (ENV === "development") { + this.logger.debug(starkUserServiceName + ": Retrieving the user profiles from the mock data"); + this.userProfiles = Deserialize(starkMockData.profiles, StarkUser); + console.log("CCR==========> this line should be kept only in DEV"); + } } public fetchUserProfile(): Observable { diff --git a/packages/stark-core/testing/tsconfig-build.json b/packages/stark-core/testing/tsconfig-build.json index cb93470532..926cf608cd 100644 --- a/packages/stark-core/testing/tsconfig-build.json +++ b/packages/stark-core/testing/tsconfig-build.json @@ -3,7 +3,15 @@ "compilerOptions": { "baseUrl": ".", "rootDir": "../", - "typeRoots": ["../node_modules/@types", "../node_modules/@nationalbankbelgium/stark-testing/node_modules/@types"], + "typeRoots": [ + "../node_modules/@types", + "../node_modules/@nationalbankbelgium/stark-testing/node_modules/@types", + "../../stark-build/typings" + ], + "paths": { + "environments/environment": ["../src/common/environment"], + "@nationalbankbelgium/stark-core": ["../"] + }, "outDir": "../../../dist/packages/stark-core" }, diff --git a/packages/stark-core/tsconfig-build.json b/packages/stark-core/tsconfig-build.json index 82cc1c8e31..c80f214602 100644 --- a/packages/stark-core/tsconfig-build.json +++ b/packages/stark-core/tsconfig-build.json @@ -3,13 +3,18 @@ "compilerOptions": { "baseUrl": ".", "rootDir": ".", - "typeRoots": ["./node_modules/@types", "./node_modules/@nationalbankbelgium/stark-testing/node_modules/@types"], + "typeRoots": [ + "./node_modules/@types", + "./node_modules/@nationalbankbelgium/stark-testing/node_modules/@types", + "../stark-build/typings" + ], "lib": ["dom", "dom.iterable", "es2017"], "paths": { "@angular/common": ["../../node_modules/@angular/common"], "@angular/core": ["../../node_modules/@angular/core"], "@angular/router": ["../../node_modules/@angular/router"], "rxjs/*": ["../../node_modules/rxjs/*"], + "environments/environment": ["./src/common/environment"], "@nationalbankbelgium/stark-core": ["."] }, "outDir": "../../dist/packages/stark-core" diff --git a/packages/tsconfig.json b/packages/tsconfig.json index ad1c9fd199..e4a87d4c51 100644 --- a/packages/tsconfig.json +++ b/packages/tsconfig.json @@ -10,6 +10,7 @@ "paths": { "rxjs/*": ["../node_modules/rxjs/*"], "@angular/*": ["../node_modules/@angular/*"], + "environments/environment": ["./stark-core/src/common/environment"], "@nationalbankbelgium/stark-*": ["./stark-*"] }, "skipDefaultLibCheck": true, @@ -17,6 +18,7 @@ "sourceMap": false, "typeRoots": [ "./stark-build/node_modules/@types", + "./stark-build/typings", "./stark-core/node_modules/@types", "./stark-testing/node_modules/@types", "./stark-ui/node_modules/@types" diff --git a/showcase/package.json b/showcase/package.json index f7f076824f..08e34b9ad8 100644 --- a/showcase/package.json +++ b/showcase/package.json @@ -55,7 +55,7 @@ "github-deploy:prod": "npm run webpack -- --config node_modules/@nationalbankbelgium/stark-build/config/webpack.github-deploy.js --progress --profile --env.githubProd", "github-deploy": "npm run github-deploy:dev", "karma": "karma", - "lint": "tslint --config tslint.json --project ./tsconfig.json --format codeFrame", + "lint": "tslint --config ./tslint.json --project ./tsconfig.json --format codeFrame", "lint-css": "stylelint \"./src/**/*.?(pc|sc|c|sa)ss\" --formatter \"string\"", "ngc": "ngc", "node": "node", @@ -63,7 +63,7 @@ "postversion": "git push && git push --tags", "preclean:install": "npm run clean", "precommit": "lint-staged", - "prettier-check": "prettier **/*.{css,js,json,pcss,scss,ts} --write", + "prettier-check": "prettier **/*.{css,js,json,md,pcss,scss,ts} --write", "preversion": "npm test", "protractor": "protractor", "protractor:delay": "sleep 3 && npm run protractor", @@ -100,7 +100,7 @@ "webpack": "node --max_old_space_size=4096 node_modules/webpack/bin/webpack.js" }, "lint-staged": { - "*.{css,js,json,pcss,scss,ts}": [ + "*.{css,js,json,md,pcss,scss,ts}": [ "prettier --write", "git add" ] @@ -119,8 +119,8 @@ "@angular/platform-browser-dynamic": "6.0.4", "@angular/platform-server": "6.0.4", "@angular/router": "6.0.4", - "@nationalbankbelgium/stark-core": "file:../dist/packages-dist/stark-core/nationalbankbelgium-stark-core-10.0.0-alpha.2-e075cf5.tgz", - "@nationalbankbelgium/stark-ui": "file:../dist/packages-dist/stark-ui/nationalbankbelgium-stark-ui-10.0.0-alpha.2-e075cf5.tgz", + "@nationalbankbelgium/stark-core": "file:../dist/packages-dist/stark-core/nationalbankbelgium-stark-core-10.0.0-alpha.2-cc6c889.tgz", + "@nationalbankbelgium/stark-ui": "file:../dist/packages-dist/stark-ui/nationalbankbelgium-stark-ui-10.0.0-alpha.2-cc6c889.tgz", "@uirouter/visualizer": "6.0.0", "core-js": "2.5.7", "eligrey-classlist-js-polyfill": "1.2.20180112", @@ -135,11 +135,12 @@ "zone.js": "0.8.26" }, "devDependencies": { - "@nationalbankbelgium/stark-build": "file:../dist/packages-dist/stark-build/nationalbankbelgium-stark-build-10.0.0-alpha.2-18ddc7a.tgz", - "@nationalbankbelgium/stark-testing": "file:../dist/packages-dist/stark-testing/nationalbankbelgium-stark-testing-10.0.0-alpha.2-18ddc7a.tgz", + "@nationalbankbelgium/stark-build": "file:../dist/packages-dist/stark-build/nationalbankbelgium-stark-build-10.0.0-alpha.2-cc6c889.tgz", + "@nationalbankbelgium/stark-testing": "file:../dist/packages-dist/stark-testing/nationalbankbelgium-stark-testing-10.0.0-alpha.2-cc6c889.tgz", "@types/core-js": "2.5.0", "@types/hammerjs": "2.0.35", "@types/node": "8.10.15", + "@types/webpack-env": "1.13.6", "@compodoc/compodoc": "1.1.3", "cross-env": "^5.1.5", "find-root": "^1.1.0", diff --git a/showcase/src/custom-typings.d.ts b/showcase/src/custom-typings.d.ts index a0fb47a290..e1b0c30390 100644 --- a/showcase/src/custom-typings.d.ts +++ b/showcase/src/custom-typings.d.ts @@ -56,9 +56,6 @@ declare module 'modern-lru' { } */ -// Extra variables that live on Global that will be replaced by webpack DefinePlugin -declare var ENV: string; -declare var HMR: boolean; declare var System: SystemJS; interface SystemJS { @@ -66,8 +63,8 @@ interface SystemJS { } interface GlobalEnvironment { - ENV: string; - HMR: boolean; + ENV: typeof ENV; + HMR: typeof HMR; SystemJS: SystemJS; System: SystemJS; } @@ -83,40 +80,11 @@ interface AsyncRoutes { type IdleCallbacks = Es6PromiseLoader | Function | FactoryEs6PromiseLoader | FactoryPromise; -interface WebpackModule { - hot: { - data?: any; - idle: any; - accept(dependencies?: string | string[], callback?: (updatedDependencies?: any) => void): void; - decline(deps?: any | string | string[]): void; - dispose(callback?: (data?: any) => void): void; - addDisposeHandler(callback?: (data?: any) => void): void; - removeDisposeHandler(callback?: (data?: any) => void): void; - check(autoApply?: any, callback?: (err?: Error, outdatedModules?: any[]) => void): void; - apply(options?: any, callback?: (err?: Error, outdatedModules?: any[]) => void): void; - status(callback?: (status?: string) => void): void | string; - removeStatusHandler(callback?: (status?: string) => void): void; - }; -} - -interface WebpackRequire { - (id: string): any; - (paths: string[], callback: (...modules: any[]) => void): void; - ensure(ids: string[], callback: (req: WebpackRequire) => void, chunkName?: string): void; - context(directory: string, useSubDirectories?: boolean, regExp?: RegExp): WebpackContext; -} - -interface WebpackContext extends WebpackRequire { - keys(): string[]; -} - interface ErrorStackTraceLimit { stackTraceLimit: number; } // Extend typings -interface NodeRequire extends WebpackRequire {} interface ErrorConstructor extends ErrorStackTraceLimit {} interface NodeRequireFunction extends Es6PromiseLoader {} -interface NodeModule extends WebpackModule {} interface Global extends GlobalEnvironment {} diff --git a/showcase/src/environments/environment.e2e.prod.ts b/showcase/src/environments/environment.e2e.prod.ts index 0f44c2b97e..15d8e6921c 100644 --- a/showcase/src/environments/environment.e2e.prod.ts +++ b/showcase/src/environments/environment.e2e.prod.ts @@ -1,10 +1,10 @@ import { enableProdMode, NgModuleRef } from "@angular/core"; import { disableDebugTools } from "@angular/platform-browser"; -import { Environment } from "./model"; +import { StarkEnvironment } from "@nationalbankbelgium/stark-core"; enableProdMode(); -export const environment: Environment = { +export const environment: StarkEnvironment = { production: true, hmr: false, diff --git a/showcase/src/environments/environment.hmr.ts b/showcase/src/environments/environment.hmr.ts index dceab97e76..8c261e855d 100644 --- a/showcase/src/environments/environment.hmr.ts +++ b/showcase/src/environments/environment.hmr.ts @@ -1,20 +1,19 @@ import { ApplicationRef, ComponentRef, NgModuleRef } from "@angular/core"; import { enableDebugTools } from "@angular/platform-browser"; -import { Environment } from "./model"; +import { StarkEnvironment } from "@nationalbankbelgium/stark-core"; // Ensure that we get detailed stack tracks during development (useful with node & Webpack) // Reference: http://stackoverflow.com/questions/7697038/more-than-10-lines-in-a-node-js-stack-error Error.stackTraceLimit = Infinity; require("zone.js/dist/long-stack-trace-zone"); -export const environment: Environment = { +export const environment: StarkEnvironment = { production: false, hmr: true, /** Angular debug tools in the dev console * https://github.com/angular/angular/blob/86405345b781a9dc2438c0fbe3e9409245647019/TOOLS_JS.md * @param modRef - * */ decorateModuleRef(modRef: NgModuleRef): NgModuleRef { const appRef: ApplicationRef = modRef.injector.get(ApplicationRef); diff --git a/showcase/src/environments/environment.prod.ts b/showcase/src/environments/environment.prod.ts index 0f44c2b97e..15d8e6921c 100644 --- a/showcase/src/environments/environment.prod.ts +++ b/showcase/src/environments/environment.prod.ts @@ -1,10 +1,10 @@ import { enableProdMode, NgModuleRef } from "@angular/core"; import { disableDebugTools } from "@angular/platform-browser"; -import { Environment } from "./model"; +import { StarkEnvironment } from "@nationalbankbelgium/stark-core"; enableProdMode(); -export const environment: Environment = { +export const environment: StarkEnvironment = { production: true, hmr: false, diff --git a/showcase/src/environments/environment.ts b/showcase/src/environments/environment.ts index 16274234ad..0b2cbeb3c0 100644 --- a/showcase/src/environments/environment.ts +++ b/showcase/src/environments/environment.ts @@ -1,11 +1,13 @@ import { ApplicationRef, ComponentRef, NgModuleRef } from "@angular/core"; import { enableDebugTools } from "@angular/platform-browser"; -import { Environment } from "./model"; +import { StarkEnvironment } from "@nationalbankbelgium/stark-core"; +// Ensure that we get detailed stack tracks during development (useful with node & Webpack) +// Reference: http://stackoverflow.com/questions/7697038/more-than-10-lines-in-a-node-js-stack-error Error.stackTraceLimit = Infinity; require("zone.js/dist/long-stack-trace-zone"); -export const environment: Environment = { +export const environment: StarkEnvironment = { production: false, hmr: false, diff --git a/showcase/src/environments/model.ts b/showcase/src/environments/model.ts deleted file mode 100644 index 547fb293c7..0000000000 --- a/showcase/src/environments/model.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { NgModuleRef } from "@angular/core"; - -export interface Environment { - production: boolean; - hmr: boolean; - ENV_PROVIDERS: any; - decorateModuleRef(modRef: NgModuleRef): NgModuleRef; -} diff --git a/showcase/src/index.html b/showcase/src/index.html index 93df1909ef..7aa96f3bc6 100644 --- a/showcase/src/index.html +++ b/showcase/src/index.html @@ -73,6 +73,18 @@ +

METADATA

+
<%= JSON.stringify(htmlWebpackPlugin.options.metadata).replace(/,/g, "\n") %>
+ +

ENV

+
<%= JSON.stringify(ENV) %>
+ +

HMR

+
<%= JSON.stringify(HMR) %>
+ +

AOT

+
<%= JSON.stringify(AOT) %>
+