Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/create command for variants configuration #2446

Open
wants to merge 59 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 48 commits
Commits
Show all changes
59 commits
Select commit Hold shift + click to select a range
ba8b36c
feat: add varinats config
ytpo-lyne Sep 10, 2024
e3c3a41
Merge branch 'main' into feat/create-variantsConfig
ytpo-lyne Sep 12, 2024
6ae06b5
Merge branch 'main' into feat/create-variantsConfig
ytpo-lyne Sep 16, 2024
631b9dc
feat: add varinats config
ytpo-lyne Sep 16, 2024
680848d
Merge branch 'main' into feat/create-variantsConfig
ytpo-lyne Sep 17, 2024
834e46d
feat: add varinats config
ytpo-lyne Sep 19, 2024
11cf9a9
Merge branch 'main' into feat/create-variantsConfig
ytpo-lyne Sep 19, 2024
77c8d58
feat: add varinats config
ytpo-lyne Sep 19, 2024
d8c41ca
feat: add varinats config
ytpo-lyne Sep 25, 2024
cdd69d0
Merge branch 'main' into feat/create-variantsConfig
ytpo-lyne Sep 25, 2024
7e4941a
feat: add varinats config
ytpo-lyne Sep 25, 2024
d10a314
adjust type in getSapClientFromPackageJson and refactor addVariantsMa…
heimwege Sep 25, 2024
8d43c14
refactor check for deprecated preview middleware and related types
heimwege Sep 26, 2024
0319d6e
fix typo
heimwege Sep 26, 2024
9a1074d
adjust log level
heimwege Sep 26, 2024
e923cc4
feat: add varinats config
ytpo-lyne Sep 27, 2024
5ba3e02
Merge branch 'main' into feat/create-variantsConfig
ytpo-lyne Sep 27, 2024
f2abaf5
add type guard
heimwege Sep 29, 2024
cda7cf9
Merge branch 'feat/create-variantsConfig' of github.com:SAP/open-ux-t…
ytpo-lyne Sep 30, 2024
71af0bb
Merge branch 'main' into feat/create-variantsConfig
ytpo-lyne Sep 30, 2024
685c0c7
test: utils and package.json
ytpo-lyne Sep 30, 2024
bdcb731
test: unit test for create command package.json and .yaml files
iha89 Oct 1, 2024
6eb12b9
Merge branch 'main' into feat/create-variantsConfig
ytpo-lyne Oct 7, 2024
ee9da52
fix typo
heimwege Oct 7, 2024
6964471
adjust unit tests
heimwege Oct 7, 2024
3db3d66
Merge branch 'feat/create-variantsConfig' of github.com:SAP/open-ux-t…
ytpo-lyne Oct 7, 2024
9cf6c87
adjust unit tests
heimwege Oct 7, 2024
600d8a9
feat: rta editor
ytpo-lyne Oct 7, 2024
27aaf52
test: unit test rta editor
ytpo-lyne Oct 7, 2024
cc2c225
Merge branch 'main' into feat/create-variantsConfig
ytpo-lyne Oct 7, 2024
29af44f
test: clean up
ytpo-lyne Oct 7, 2024
56e224b
refactoring
heimwege Oct 8, 2024
9412b87
minor refactoring
heimwege Oct 8, 2024
8125256
refactor addVariantsManagementScript
heimwege Oct 8, 2024
a0ed8d9
tiny refactoring
heimwege Oct 8, 2024
d1886e5
Merge branch 'main' into feat/create-variantsConfig
ytpo-lyne Oct 8, 2024
b54b616
Merge branch 'main' into feat/create-variantsConfig
heimwege Oct 8, 2024
0475149
Merge branch 'main' into feat/create-variantsConfig
ytpo-lyne Oct 8, 2024
4c4b869
changeset
ytpo-lyne Oct 8, 2024
1902cc7
fix: sonar
ytpo-lyne Oct 8, 2024
974f32c
add unit test
heimwege Oct 8, 2024
5055355
minor refactoring
heimwege Oct 9, 2024
f74c5f9
adjust types
heimwege Oct 9, 2024
fa20548
Merge branch 'main' into feat/create-variantsConfig
heimwege Oct 9, 2024
1adaa49
fix test data error
heimwege Oct 10, 2024
1f299c5
Merge remote-tracking branch 'origin/feat/create-variantsConfig' into…
heimwege Oct 10, 2024
c4f8e10
enhance jsDoc of readUi5Yaml
heimwege Oct 10, 2024
28efeff
refactoring
heimwege Oct 10, 2024
bc63749
Merge branch 'main' into feat/create-variantsConfig
heimwege Oct 10, 2024
93b5a14
add unit test
heimwege Oct 10, 2024
c22b0dd
add unit test
heimwege Oct 10, 2024
8be57d1
add unit test
heimwege Oct 10, 2024
e3a20bd
fix sonar issue
heimwege Oct 10, 2024
a4b9f56
Merge branch 'main' into feat/create-variantsConfig
heimwege Oct 11, 2024
22c86cf
Merge branch 'main' into feat/create-variantsConfig
heimwege Oct 13, 2024
ee1d679
feat: path to yaml by cli and error handling
ytpo-lyne Oct 15, 2024
ae367b2
test: update unit tests and readMe
ytpo-lyne Oct 15, 2024
22bb028
Merge branch 'main' into feat/create-variantsConfig
ytpo-lyne Oct 15, 2024
d69c142
Merge branch 'main' into feat/create-variantsConfig
ytpo-lyne Oct 17, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/little-ties-cry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@sap-ux/app-config-writer': patch
'@sap-ux/create': patch
---

Introduce create command to add Configuration for Variants Creation.
1 change: 1 addition & 0 deletions packages/app-config-writer/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"!dist/**/*.map"
],
"dependencies": {
"@sap-ux/preview-middleware": "workspace:*",
"@sap-ux/axios-extension": "workspace:*",
"@sap-ux/btp-utils": "workspace:*",
"@sap-ux/logger": "workspace:*",
Expand Down
1 change: 1 addition & 0 deletions packages/app-config-writer/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export { getSmartLinksTargetFromPrompt, promptInboundNavigationConfig, validateText } from './prompt';
export { generateSmartLinksConfig } from './smartlinks-config';
export { generateInboundNavigationConfig } from './navigation-config';
export { generateVariantsConfig } from './variants-config';
1 change: 1 addition & 0 deletions packages/app-config-writer/src/types/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './smartLinks';
export * from './variantsConfig';
export * from './navigation';
16 changes: 16 additions & 0 deletions packages/app-config-writer/src/types/variantsConfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import type { MiddlewareConfig as PreviewConfig } from '@sap-ux/preview-middleware';

export type FioriToolsDeprecatedPreviewConfig = {
Copy link
Contributor

@heimwege heimwege Oct 9, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@tobiasqueck There already exists a type that represents the deprecated config preview config in ui5-config/src/types/index.ts. That still seems to be used to generate outdated configs (see here). Do we need to address this in this PR as well? Or is this part of some generator adjustments that will come later because it seems to be used in app writer (here)?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this type (and previewConfigOptions) be moved to preview middleware?

component: string;
libs?: boolean;
ui5Theme?: string;
};

export type PreviewConfigOptions = FioriToolsDeprecatedPreviewConfig | PreviewConfig;

export enum MiddlewareConfigs {
FioriToolsPreview = 'fiori-tools-preview',
PreviewMiddleware = 'preview-middleware',
ReloadMiddleware = 'reload-middleware',
FioriToolsAppreload = 'fiori-tools-appreload'
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { create } from 'mem-fs-editor';
import { create as createStorage } from 'mem-fs';
import { updateMiddlewares } from './ui5-yaml';
import { addVariantsManagementScript } from './package-json';
import type { Editor } from 'mem-fs-editor';
import type { ToolsLogger } from '@sap-ux/logger';

/**
* Add variants configuration to an app or project.
*
* @param basePath - the base path where the package.json and ui5.yaml is
* @param logger - logger
* @param fs - the memfs editor instance
* @returns Promise<Editor> - memfs editor instance with updated files
*/
export async function generateVariantsConfig(basePath: string, logger?: ToolsLogger, fs?: Editor): Promise<Editor> {
if (!fs) {
fs = create(createStorage());
}
await addVariantsManagementScript(fs, basePath, logger).catch((error) => {
logger?.error(`Script 'start-variants-management' cannot be written to package.json. ${error.message}.`);
return fs;
});
await updateMiddlewares(fs, basePath, logger);
return fs;
}
1 change: 1 addition & 0 deletions packages/app-config-writer/src/variants-config/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './generateVariantsConfig';
48 changes: 48 additions & 0 deletions packages/app-config-writer/src/variants-config/package-json.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { join } from 'path';
import { getSapClientFromPackageJson, getUI5UrlParameters, getRTAUrl } from './utils';
import type { Editor } from 'mem-fs-editor';
import type { Package } from '@sap-ux/project-access';
import type { ToolsLogger } from '@sap-ux/logger';

/**
* Add the start-variants-management script to the package.json.
*
* @param fs - mem-fs reference to be used for file access
* @param basePath - path to application root, where package.json is
* @param logger - logger
* @returns Promise<void> - rejects in case variants management script can't be added to package.json
*/
export async function addVariantsManagementScript(fs: Editor, basePath: string, logger?: ToolsLogger): Promise<void> {
const packageJsonPath = join(basePath, 'package.json');
const packageJson = fs.readJSON(packageJsonPath) as Package | undefined;

if (!packageJson) {
return Promise.reject(new Error(`File 'package.json' not found at ${basePath}`));
}

if (packageJson?.scripts?.['start-variants-management']) {
return Promise.reject(new Error(`Script already exists.`));
}

if (!packageJson.scripts) {
logger?.warn(`File 'package.json' does not contain a script section. Script section added.`);
packageJson.scripts = {};
}

const urlParameters: Record<string, string> = {};
const sapClient = getSapClientFromPackageJson(packageJson.scripts);
if (sapClient) {
urlParameters['sap-client'] = sapClient;
}

const url = await getRTAUrl(basePath, getUI5UrlParameters(urlParameters));

if (!url) {
return Promise.reject(new Error(`No RTA editor specified in ui5.yaml.`));
}

packageJson.scripts['start-variants-management'] = `fiori run --open "${url}"`;
fs.writeJSON(packageJsonPath, packageJson);
logger?.debug(`Script 'start-variants-management' written to 'package.json'.`);
return Promise.resolve();
}
91 changes: 91 additions & 0 deletions packages/app-config-writer/src/variants-config/ui5-yaml.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { join } from 'path';
import { MiddlewareConfigs } from '../types';
import { FileName, type Package, readUi5Yaml } from '@sap-ux/project-access';
import type { Editor } from 'mem-fs-editor';
import type { ToolsLogger } from '@sap-ux/logger';
import type { PreviewConfigOptions } from '../types';
import type { CustomMiddleware, FioriAppReloadConfig, UI5Config } from '@sap-ux/ui5-config';
import { getPreviewMiddleware } from './utils';

/**
* Gets the reload middleware form the provided yamlConfig.
* The middleware can either be named 'fiori-tools-appreload' or 'reload-middleware'.
* If the middleware is found, a delay of 300ms will be inserted.
*
* @param yamlConfig - the yaml configuration to use
* @returns reload middleware configuration if found or undefined
*/
export async function getEnhancedReloadMiddleware(
yamlConfig: UI5Config
): Promise<CustomMiddleware<FioriAppReloadConfig> | undefined> {
const reloadMiddleware =
yamlConfig.findCustomMiddleware<FioriAppReloadConfig>(MiddlewareConfigs.FioriToolsAppreload) ??
yamlConfig.findCustomMiddleware<FioriAppReloadConfig>(MiddlewareConfigs.ReloadMiddleware);
if (!reloadMiddleware) {
return undefined;
}
if (!reloadMiddleware?.configuration?.delay) {
reloadMiddleware.configuration = { ...reloadMiddleware.configuration, delay: 300 };
}
return reloadMiddleware;
}

/**
* Creates a preview middleware configuration based on the presence of the @sap/ux-ui5-tooling dependency.
*
* @param fs - mem-fs reference to be used for file access
* @param basePath - path to project root, where package.json and ui5.yaml is
* @returns 'fiori-tools-preview' or 'preview-middleware' configuration
*/
export function createPreviewMiddlewareConfig(fs: Editor, basePath: string): CustomMiddleware<PreviewConfigOptions> {
const packageJsonPath = join(basePath, 'package.json');
const packageJson = fs.readJSON(packageJsonPath) as Package | undefined;
return {
name: packageJson?.devDependencies?.['@sap/ux-ui5-tooling']
? MiddlewareConfigs.FioriToolsPreview
: MiddlewareConfigs.PreviewMiddleware,
afterMiddleware: 'compression'
} as CustomMiddleware<PreviewConfigOptions>;
}

/**
* Checks the project for ui5.yaml files and reads out the configuration to update the preview and reload middlewares.
* If a reload middleware exists, then a delay of 300ms will be inserted and the preview middleware will be set afterward.
*
* @param fs - mem-fs reference to be used for file access
* @param basePath - path to project root, where package.json and ui5.yaml is
* @param logger - logger
*/
export async function updateMiddlewares(fs: Editor, basePath: string, logger?: ToolsLogger): Promise<void> {
const ui5Yamls = [FileName.Ui5Yaml, FileName.Ui5MockYaml, FileName.Ui5LocalYaml];
for (const ui5Yaml of ui5Yamls) {
let ui5YamlConfig: UI5Config;

try {
ui5YamlConfig = await readUi5Yaml(basePath, ui5Yaml);
} catch (error) {
logger?.debug((error as Error).message);
continue;
}

let previewMiddleware = await getPreviewMiddleware(ui5YamlConfig);

if (!previewMiddleware) {
logger?.warn(`No preview middleware found in ${ui5Yaml}. Preview middleware will be added.`);
previewMiddleware = createPreviewMiddlewareConfig(fs, basePath);
}

const reloadMiddleware = await getEnhancedReloadMiddleware(ui5YamlConfig);

if (reloadMiddleware) {
previewMiddleware.afterMiddleware = reloadMiddleware.name;
ui5YamlConfig.updateCustomMiddleware(reloadMiddleware);
logger?.debug(`Updated reload middleware in ${ui5Yaml}.`);
}

ui5YamlConfig.updateCustomMiddleware(previewMiddleware);
const yamlPath = join(basePath, ui5Yaml);
fs.write(yamlPath, ui5YamlConfig.toString());
logger?.debug(`Updated preview middleware in ${ui5Yaml}.`);
}
}
139 changes: 139 additions & 0 deletions packages/app-config-writer/src/variants-config/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import { FileName, readUi5Yaml } from '@sap-ux/project-access';
import { MiddlewareConfigs } from '../types';
import { stringify } from 'querystring';
import type { Package } from '@sap-ux/project-access';
import type { CustomMiddleware, UI5Config } from '@sap-ux/ui5-config';
import type { PreviewConfigOptions, FioriToolsDeprecatedPreviewConfig } from '../types';

/**
* Gets the preview middleware form the yamlConfig or provided path.
* The middleware can either be named 'fiori-tools-preview' or 'preview-middleware'.
*
* @param yamlConfig - the yaml configuration to use; if not provided, the file will be read with the provided basePath and filename
* @param basePath - path to project root, where ui5.yaml is located
* @param filename - name of the ui5 yaml file to read from basePath; default is 'ui5.yaml'
* @returns preview middleware configuration if found or undefined
* @throws {Error} if filename is not found at basePath
* @throws {Error} if basePath and yamlConfig are undefined
*/
export async function getPreviewMiddleware(
yamlConfig?: UI5Config,
basePath?: string,
filename: string = FileName.Ui5Yaml
): Promise<CustomMiddleware<PreviewConfigOptions> | undefined> {
if (!basePath && !yamlConfig) {
throw new Error('Either base path or yaml config must be provided');
}
yamlConfig = yamlConfig ?? (await readUi5Yaml(basePath!, filename));
return (
yamlConfig.findCustomMiddleware<PreviewConfigOptions>(MiddlewareConfigs.FioriToolsPreview) ??
yamlConfig.findCustomMiddleware<PreviewConfigOptions>(MiddlewareConfigs.PreviewMiddleware)
);
}

/**
* Type guard to check if the given configuration is a deprecated preview middleware configuration.
*
* @param configuration preview middleware configuration
* @returns true, if a preview middleware configuration is deprecated
*/
function isFioriToolsDeprecatedPreviewConfig(
configuration: PreviewConfigOptions | undefined
): configuration is FioriToolsDeprecatedPreviewConfig {
return (configuration as FioriToolsDeprecatedPreviewConfig)?.component !== undefined;
}

/**
* Extracts sap client string from existing scripts in package.json.
*
* @param scripts - script section of the package.json
* @returns sap client
*/
export function getSapClientFromPackageJson(scripts: Package['scripts']): string | undefined {
for (const value of Object.values(scripts!)) {
const match = value?.match(/sap-client=(\d{3})/);
if (match) {
return match[1];
}
}
return undefined;
}

/**
* Returns the UI5 url parameters.
* This is needed for the UI5 run time adaptation.
*
* @param overwritingParams - parameters to be overwritten
* @returns - UI5 url parameters
*/
export function getUI5UrlParameters(overwritingParams: Record<string, string> = {}): string {
const parameters: Record<string, string> = {
'fiori-tools-rta-mode': 'true',
'sap-ui-rta-skip-flex-validation': 'true',
'sap-ui-xx-condense-changes': 'true'
};
return stringify(Object.assign(parameters, overwritingParams));
}

/**
* Returns the RTA mount point of the preview middleware configuration from the ui5.yaml file, if given.
*
* @param previewMiddlewareConfig - configuration of the preview middleware
* @returns - RTA mount point or undefined
*/
function getRTAMountPoint(previewMiddlewareConfig: PreviewConfigOptions | undefined): string | undefined {
if (!isFioriToolsDeprecatedPreviewConfig(previewMiddlewareConfig) && previewMiddlewareConfig?.rta?.editors) {
const editors = previewMiddlewareConfig.rta.editors;
for (const editor of editors) {
if (!('developerMode' in editor)) {
return editor.path;
}
}
}
return undefined;
}

/**
* Returns the intent of the preview middleware configuration from the ui5.yaml file, if given.
*
* @param previewMiddlewareConfig - configuration of the preview middleware
* @returns - preview intent or undefined
*/
function getRTAIntent(previewMiddlewareConfig: PreviewConfigOptions | undefined): string | undefined {
if (isFioriToolsDeprecatedPreviewConfig(previewMiddlewareConfig)) {
return undefined;
}
const intent = previewMiddlewareConfig?.flp?.intent;
return intent ? `#${intent.object}-${intent.action}` : undefined;
}

/**
* Returns the url for variants management in RTA mode.
* The url consist of a specified mount point and intent given from the ui5.yaml file as well as parameters for the RTA mode.
*
* @param basePath - path to project root, where package.json and ui5.yaml is located
* @param query - query to create fragment
* @returns - review url parameters
*/
export async function getRTAUrl(basePath: string, query: string): Promise<string | undefined> {
let previewMiddleware: CustomMiddleware<PreviewConfigOptions> | undefined;
try {
previewMiddleware = await getPreviewMiddleware(undefined, basePath);
} catch (error) {
//todo: what to do in case there is no ui5.yaml file? try FileName.Ui5MockYaml or FileName.Ui5LocalYaml as fallback?
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@tobiasqueck you thoughts about potential fallbacks for RTA editor path?

return undefined;
}

if (
previewMiddleware?.name === MiddlewareConfigs.PreviewMiddleware &&
!getRTAMountPoint(previewMiddleware?.configuration)
) {
return undefined;
}
const mountPoint = getRTAMountPoint(previewMiddleware?.configuration) ?? '/preview.html';
const intent = getRTAIntent(previewMiddleware?.configuration) ?? '#app-preview';

return isFioriToolsDeprecatedPreviewConfig(previewMiddleware?.configuration)
? `${mountPoint}?${query}#preview-app`
: `${mountPoint}?${query}${intent}`;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"name": "v2-lrop-0909",
"description": "An SAP Fiori application.",
"scripts": {
"start-variants-management": "fiori run --open \"preview.html?fiori-tools-rta-mode=true&sap-ui-rta-skip-flex-validation=true&sap-ui-xx-condense-changes=true&sap-client=500#app-preview\""
},
"sapux": true,
"sapuxLayer": "VENDOR"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
specVersion: "3.1"
metadata:
name: v2lrop0909
type: application
server:
customMiddleware:
- name: fiori-tools-preview
afterMiddleware: compression
configuration:
component: v2lrop0909
ui5Theme: sap_horizon
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"name": "test-app",
"description": "An SAP Fiori application.",
"scripts": {
"start": "fiori run --open \"test/flpSandbox.html?sap-client=500#test-app\""
},
"sapux": true,
"sapuxLayer": "VENDOR"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
specVersion: "3.1"
metadata:
name: fiori-tools-config
type: application
server:
customMiddleware:
- name: fiori-tools-appreload
afterMiddleware: compression
- name: fiori-tools-preview
afterMiddleware: compression
Loading
Loading