@sap-ux/cf-deploy-config-writer 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +84 -0
  3. package/dist/cf-writer/app-config.d.ts +21 -0
  4. package/dist/cf-writer/app-config.js +368 -0
  5. package/dist/cf-writer/base-config.d.ts +13 -0
  6. package/dist/cf-writer/base-config.js +143 -0
  7. package/dist/cf-writer/index.d.ts +3 -0
  8. package/dist/cf-writer/index.js +8 -0
  9. package/dist/constants.d.ts +111 -0
  10. package/dist/constants.js +115 -0
  11. package/dist/i18n.d.ts +14 -0
  12. package/dist/i18n.js +40 -0
  13. package/dist/index.d.ts +5 -0
  14. package/dist/index.js +24 -0
  15. package/dist/logger-helper.d.ts +20 -0
  16. package/dist/logger-helper.js +27 -0
  17. package/dist/mta-config/index.d.ts +43 -0
  18. package/dist/mta-config/index.js +101 -0
  19. package/dist/mta-config/mta.d.ts +242 -0
  20. package/dist/mta-config/mta.js +874 -0
  21. package/dist/translations/cf-deploy-config-writer.i18n.json +25 -0
  22. package/dist/types/index.d.ts +89 -0
  23. package/dist/types/index.js +14 -0
  24. package/dist/utils.d.ts +91 -0
  25. package/dist/utils.js +149 -0
  26. package/package.json +62 -0
  27. package/templates/app/mta-ext.mtaext +25 -0
  28. package/templates/app/mta.yaml +12 -0
  29. package/templates/app/xs-app-destination.json +31 -0
  30. package/templates/app/xs-app-no-destination.json +24 -0
  31. package/templates/common/xs-security.json +7 -0
  32. package/templates/gitignore.tmpl +10 -0
  33. package/templates/package.json +15 -0
  34. package/templates/router/package.json +18 -0
  35. package/templates/router/xs-app-abapservice.json +25 -0
  36. package/templates/router/xs-app-server.json +17 -0
  37. package/templates/router/xs-app.json +18 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,84 @@
1
+ # @sap-ux/cf-deploy-config-writer
2
+
3
+ Add or amend Cloud Foundry deployment configuration to SAP projects.
4
+
5
+ ## Prerequisites
6
+ * For CAP Projects a CDS binary is required, for more information refer to the [CDS Tool](https://www.npmjs.com/package/@sap/cds)
7
+ * For HTML5 Projects an MTA binary is required, for more information refer to the [MTA Tool](https://www.npmjs.com/package/mta), this is required to support the [mta-lib](https://www.npmjs.com/package/@sap/mta-lib) library which handles the flows for interacting with the `mta.yaml` configuration.
8
+
9
+ ## Installation
10
+ Npm
11
+ `npm install --save @sap-ux/cf-deploy-config-writer`
12
+
13
+ Yarn
14
+ `yarn add @sap-ux/cf-deploy-config-writer`
15
+
16
+ Pnpm
17
+ `pnpm add @sap-ux/cf-deploy-config-writer`
18
+
19
+ ## Usage
20
+ Calling the MtaConfig library to add routing modules, HTML5 apps, destinations, and mta extension configurations to an existing MTA configuration file. Dependent on the [MTA Tool](https://www.npmjs.com/package/mta) for exploring and validating the changes being made.
21
+ ```Typescript
22
+ import { MtaConfig } from '@sap-ux/cf-deploy-config-writer';
23
+ // Create a new instance of MtaConfig
24
+ const mtaConfig = await MtaConfig.newInstance('path/to/mta.yaml');
25
+ // Carry out some operations...
26
+ // 1. Add routing modules and also add managed approuter configuration
27
+ await mtaConfig.addRoutingModules(true);
28
+ // 2. Add new HTML5 app
29
+ await mtaConfig.addApp('myui5app', './');
30
+ // 3. Append a destination instance to the destination service, required by consumers of CAP services (e.g. approuter, destinations)
31
+ await mtaConfig.appendInstanceBasedDestination('mynewdestination');
32
+ // 4. Append mta extension configuration
33
+ await mtaConfig.addMtaExtensionConfig('mynewdestination', 'https://my-service-url.base', {
34
+ key: 'ApiKey',
35
+ value: `${apiHubKey}`
36
+ });
37
+ // 5. Save changes
38
+ await mtaConfig.save();
39
+ ```
40
+
41
+ Calling the `generateAppConfig` function to append Cloud Foundry configuration to a HTML5 application;
42
+ ```Typescript
43
+ import { generateAppConfig, DefaultMTADestination } from '@sap-ux/cf-deploy-config-writer'
44
+ import { join } from 'path';
45
+
46
+ const exampleWriter = async () => {
47
+ const appPath = join(__dirname, 'testapp');
48
+ // Append managed approuter configuration, toggle `cfAddManagedAppRouter` to false to ommit the managed approuter configuration being appended to the mta.yaml
49
+ const fs = await generateAppConfig({appPath, destinationName: 'SAPBTPDestination'});
50
+ // For CAP flows, set the destination to DefaultMTADestination to create a destination service instance between the HTML5 and CAP Project
51
+ const fs = await generateAppConfig({appPath, addManagedAppRouter: true, destinationName: DefaultMTADestination});
52
+ return new Promise((resolve) => {
53
+ fs.commit(resolve); // When using with Yeoman it handle the fs commit.
54
+ });
55
+ }
56
+ // Calling the function
57
+ await exampleWriter();
58
+ ```
59
+
60
+ Calling the `generateBaseConfig` function to generate a `new` Cloud Foundry configuration, supporting managed | standalone configurations;
61
+ ```Typescript
62
+ import { generateBaseConfig, RouterModuleType } from '@sap-ux/cf-deploy-config-writer'
63
+ import { join } from 'path';
64
+
65
+ const exampleWriter = async () => {
66
+ const mtaPath = join(__dirname, 'testapp');
67
+ // Generate a managed approuter configuration, toggle the routerType to Standard for a standalone configuration
68
+ const fs = await generateBaseConfig({ mtaId: 'myapp', routerType: RouterModuleType.Managed, mtaPath });
69
+ return new Promise((resolve) => {
70
+ fs.commit(resolve); // When using with Yeoman it handle the fs commit.
71
+ });
72
+ }
73
+ // Calling the function
74
+ await exampleWriter();
75
+ ```
76
+
77
+ ## Keywords
78
+ SAP Fiori elements
79
+ SAP UI5
80
+ SAP Deployment
81
+ Cloud Foundry
82
+ MTA
83
+ Multi-Target Application
84
+
@@ -0,0 +1,21 @@
1
+ import { type Editor } from 'mem-fs-editor';
2
+ import { type Logger } from '@sap-ux/logger';
3
+ import { type CFConfig, type CFAppConfig } from '../types';
4
+ /**
5
+ * Add a managed approuter configuration to an existing HTML5 application.
6
+ *
7
+ * @param cfAppConfig writer configuration
8
+ * @param fs an optional reference to a mem-fs editor
9
+ * @param logger optional logger instance
10
+ * @returns file system reference
11
+ */
12
+ export declare function generateAppConfig(cfAppConfig: CFAppConfig, fs?: Editor, logger?: Logger): Promise<Editor>;
13
+ /**
14
+ * Generate UI5 deploy config.
15
+ *
16
+ * @param cfConfig - the deploy config
17
+ * @param fs reference to a mem-fs editor
18
+ * @returns the deploy config
19
+ */
20
+ export declare function generateUI5DeployConfig(cfConfig: CFConfig, fs: Editor): Promise<void>;
21
+ //# sourceMappingURL=app-config.d.ts.map
@@ -0,0 +1,368 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.generateAppConfig = generateAppConfig;
7
+ exports.generateUI5DeployConfig = generateUI5DeployConfig;
8
+ const path_1 = require("path");
9
+ const child_process_1 = require("child_process");
10
+ const mem_fs_1 = require("mem-fs");
11
+ const mem_fs_editor_1 = require("mem-fs-editor");
12
+ const hasbin_1 = require("hasbin");
13
+ const ui5_config_1 = require("@sap-ux/ui5-config");
14
+ const project_access_1 = require("@sap-ux/project-access");
15
+ const btp_utils_1 = require("@sap-ux/btp-utils");
16
+ const constants_1 = require("../constants");
17
+ const utils_1 = require("../utils");
18
+ const mta_config_1 = require("../mta-config");
19
+ const logger_helper_1 = __importDefault(require("../logger-helper"));
20
+ const i18n_1 = require("../i18n");
21
+ /**
22
+ * Add a managed approuter configuration to an existing HTML5 application.
23
+ *
24
+ * @param cfAppConfig writer configuration
25
+ * @param fs an optional reference to a mem-fs editor
26
+ * @param logger optional logger instance
27
+ * @returns file system reference
28
+ */
29
+ async function generateAppConfig(cfAppConfig, fs, logger) {
30
+ if (!fs) {
31
+ fs = (0, mem_fs_editor_1.create)((0, mem_fs_1.create)());
32
+ }
33
+ if (logger) {
34
+ logger_helper_1.default.logger = logger;
35
+ }
36
+ validateMtaConfig();
37
+ await generateDeployConfig(cfAppConfig, fs);
38
+ return fs;
39
+ }
40
+ /**
41
+ * Validate the conditions to allow deployment configuration to be added.
42
+ *
43
+ */
44
+ function validateMtaConfig() {
45
+ // CF writer is dependent on the mta-lib library, which in turn relies on the mta executable being installed and available in the path
46
+ if (!(0, hasbin_1.sync)(constants_1.MTAExecutable)) {
47
+ throw new Error(constants_1.MTABinNotFound);
48
+ }
49
+ }
50
+ /**
51
+ * Returns the updated configuration for the given HTML5 app, after reading all the required files.
52
+ *
53
+ * @param cfAppConfig writer configuration
54
+ * @param fs reference to a mem-fs editor
55
+ * @returns updated writer configuration
56
+ */
57
+ async function getUpdatedConfig(cfAppConfig, fs) {
58
+ const isLCAP = cfAppConfig.lcapMode ?? false;
59
+ const { rootPath, isCap, mtaId, mtaPath, hasRoot, capRoot } = await getProjectProperties(cfAppConfig);
60
+ const { serviceHost, destination } = await processUI5Config(cfAppConfig.appPath, fs);
61
+ const { servicePath, firstServicePathSegment, appId } = await processManifest(cfAppConfig.appPath, fs);
62
+ const { isFullUrlDest, destinationAuthType } = await (0, utils_1.getDestinationProperties)(cfAppConfig.destinationName ?? destination);
63
+ const config = {
64
+ appPath: cfAppConfig.appPath.replace(/\/$/, ''),
65
+ destinationName: cfAppConfig.destinationName ?? destination,
66
+ addManagedAppRouter: cfAppConfig.addManagedAppRouter ?? true,
67
+ lcapMode: !isCap ? false : isLCAP, // Restricting local changes is only applicable for CAP flows
68
+ isMtaRoot: hasRoot ?? false,
69
+ serviceHost: cfAppConfig.serviceHost ?? serviceHost,
70
+ rootPath: rootPath.replace(/\/$/, ''),
71
+ mtaId,
72
+ mtaPath,
73
+ destinationAuthType,
74
+ isCap,
75
+ servicePath,
76
+ firstServicePathSegment,
77
+ appId,
78
+ capRoot,
79
+ isFullUrlDest
80
+ };
81
+ logger_helper_1.default.logger?.debug(`CF Config loaded: ${JSON.stringify(config, null, 2)}`);
82
+ return config;
83
+ }
84
+ /**
85
+ * Get project properties.
86
+ *
87
+ * @param config writer configuration
88
+ * @returns project properties
89
+ */
90
+ async function getProjectProperties(config) {
91
+ let isCap = false;
92
+ let rootPath;
93
+ let mtaPath;
94
+ let mtaId;
95
+ const foundMtaPath = await (0, project_access_1.getMtaPath)(config.appPath);
96
+ if (foundMtaPath) {
97
+ mtaPath = (0, path_1.dirname)(foundMtaPath.mtaPath);
98
+ mtaId = await (0, mta_config_1.getMtaId)(mtaPath);
99
+ }
100
+ const hasRoot = foundMtaPath?.hasRoot ?? false;
101
+ const capRoot = (await (0, project_access_1.findCapProjectRoot)(config.appPath)) ?? undefined;
102
+ if (capRoot) {
103
+ // CDS executable is required for CAP projects as the mta.yaml file is generated by the cds deploy command
104
+ if (!(0, hasbin_1.sync)(constants_1.CDSExecutable)) {
105
+ throw new Error(constants_1.CDSBinNotFound);
106
+ }
107
+ isCap = true;
108
+ rootPath = capRoot;
109
+ }
110
+ else {
111
+ rootPath = mtaPath ?? config.appPath;
112
+ }
113
+ return { rootPath, isCap, mtaId, mtaPath, hasRoot, capRoot };
114
+ }
115
+ /**
116
+ * Reads the ui5.yaml file and returns the service base, firstServicePathSegment and destination if found.
117
+ *
118
+ * @param appPath path to the application
119
+ * @param fs reference to a mem-fs editor
120
+ * @returns serviceBase, firstServicePathSegment and destination properties
121
+ */
122
+ async function processUI5Config(appPath, fs) {
123
+ let destination;
124
+ let serviceHost;
125
+ let firstServicePathSegment;
126
+ try {
127
+ const ui5YamlConfig = await (0, project_access_1.readUi5Yaml)(appPath, project_access_1.FileName.Ui5Yaml, fs);
128
+ const toolsConfig = ui5YamlConfig.findCustomMiddleware('fiori-tools-proxy');
129
+ if (toolsConfig?.configuration?.backend?.length === 1) {
130
+ destination = toolsConfig?.configuration?.backend[0].destination;
131
+ serviceHost = toolsConfig?.configuration?.backend[0].url;
132
+ firstServicePathSegment = toolsConfig?.configuration?.backend[0].path;
133
+ }
134
+ }
135
+ catch (error) {
136
+ logger_helper_1.default.logger?.debug((0, i18n_1.t)('debug.ui5YamlDoesNotExist'));
137
+ }
138
+ return { destination, serviceHost, firstServicePathSegment };
139
+ }
140
+ /**
141
+ * Reads the manifest.json file and returns the service path, firstServicePathSegment and appId if found.
142
+ *
143
+ * @param appPath path to the application
144
+ * @param fs reference to a mem-fs editor
145
+ * @returns servicePath, firstServicePathSegment and appId properties
146
+ */
147
+ async function processManifest(appPath, fs) {
148
+ const manifest = await (0, utils_1.readManifest)((0, path_1.join)(appPath, 'webapp/manifest.json'), fs);
149
+ const appId = manifest?.['sap.app']?.id ? (0, mta_config_1.toMtaModuleName)(manifest?.['sap.app']?.id) : undefined;
150
+ const servicePath = manifest?.['sap.app']?.dataSources?.mainService?.uri;
151
+ const firstServicePathSegment = servicePath?.substring(0, servicePath?.indexOf('/', 1));
152
+ return { servicePath, firstServicePathSegment, appId };
153
+ }
154
+ /**
155
+ *
156
+ * @param cfAppConfig writer configuration
157
+ * @param fs reference to a mem-fs editor
158
+ */
159
+ async function generateDeployConfig(cfAppConfig, fs) {
160
+ const cfConfig = await getUpdatedConfig(cfAppConfig, fs);
161
+ // Generate MTA Config, LCAP will generate the mta.yaml on the fly so we dont care about it!
162
+ if (!cfConfig.lcapMode) {
163
+ createMTAConfig(cfConfig);
164
+ await generateSupportingConfig(cfConfig, fs);
165
+ await updateMtaConfig(cfConfig);
166
+ }
167
+ // Generate HTML5 config
168
+ await appendCloudFoundryConfigurations(cfConfig, fs);
169
+ await updateManifest(cfConfig, fs);
170
+ await updateHTML5AppPackage(cfConfig, fs);
171
+ await updateRootPackage(cfConfig, fs);
172
+ }
173
+ /**
174
+ * Creates the MTA configuration file.
175
+ *
176
+ * @param cfConfig writer configuration
177
+ */
178
+ function createMTAConfig(cfConfig) {
179
+ if (!cfConfig.mtaId) {
180
+ if (cfConfig.isCap) {
181
+ const result = (0, child_process_1.spawnSync)(constants_1.CDSExecutable, constants_1.CDSAddMtaParams, {
182
+ cwd: cfConfig.rootPath
183
+ });
184
+ if (result.error) {
185
+ throw new Error(constants_1.CDSBinNotFound);
186
+ }
187
+ }
188
+ else {
189
+ (0, mta_config_1.createMTA)({ mtaId: cfConfig.appId, mtaPath: cfConfig.mtaPath ?? cfConfig.rootPath });
190
+ }
191
+ cfConfig.mtaId = cfConfig.appId;
192
+ cfConfig.mtaPath = cfConfig.rootPath;
193
+ }
194
+ }
195
+ /**
196
+ * Generate CF specific configurations to support deployment and undeployment.
197
+ *
198
+ * @param config writer configuration
199
+ * @param fs reference to a mem-fs editor
200
+ */
201
+ async function generateSupportingConfig(config, fs) {
202
+ const mtaId = config.mtaId ?? (await (0, mta_config_1.getMtaId)(config.rootPath));
203
+ // Add specific MTA ID configurations
204
+ const mtaConfig = { mtaId: mtaId ?? config.appId, mtaPath: config.rootPath };
205
+ if (mtaId && !fs.exists((0, path_1.join)(config.rootPath, 'package.json'))) {
206
+ (0, utils_1.addRootPackage)(mtaConfig, fs);
207
+ }
208
+ if (config.addManagedAppRouter && !fs.exists((0, path_1.join)(config.rootPath, constants_1.XSSecurityFile))) {
209
+ (0, utils_1.addXSSecurityConfig)(mtaConfig, fs);
210
+ }
211
+ // Be a good developer and add a .gitignore if missing from the existing project root
212
+ if (!fs.exists((0, path_1.join)(config.rootPath, '.gitignore'))) {
213
+ (0, utils_1.addGitIgnore)(config.rootPath, fs);
214
+ }
215
+ }
216
+ /**
217
+ * Updates the MTA configuration file.
218
+ *
219
+ * @param cfConfig writer configuration
220
+ */
221
+ async function updateMtaConfig(cfConfig) {
222
+ const mtaInstance = await (0, mta_config_1.getMtaConfig)(cfConfig.rootPath);
223
+ if (mtaInstance) {
224
+ await mtaInstance.addRoutingModules(cfConfig.addManagedAppRouter);
225
+ const appModule = cfConfig.appId;
226
+ const appRelativePath = (0, utils_1.toPosixPath)((0, path_1.relative)(cfConfig.rootPath, cfConfig.appPath));
227
+ await mtaInstance.addApp(appModule, appRelativePath ?? '.');
228
+ await (0, mta_config_1.addMtaDeployParameters)(mtaInstance);
229
+ if ((cfConfig.destinationName && cfConfig.isCap) || cfConfig.destinationName === constants_1.DefaultMTADestination) {
230
+ // If the destination instance identifier is passed, create a destination instance
231
+ cfConfig.destinationName =
232
+ cfConfig.destinationName === constants_1.DefaultMTADestination
233
+ ? mtaInstance.getFormattedPrefix(constants_1.ResourceMTADestination)
234
+ : cfConfig.destinationName;
235
+ await mtaInstance.appendInstanceBasedDestination(cfConfig.destinationName);
236
+ // This is required where a managed or standalone router hasnt been added yet to mta.yaml
237
+ if (!mtaInstance.hasManagedXsuaaResource()) {
238
+ cfConfig.destinationAuthType = btp_utils_1.Authentication.NO_AUTHENTICATION;
239
+ }
240
+ }
241
+ await saveMta(cfConfig, mtaInstance);
242
+ cfConfig.cloudServiceName = mtaInstance.cloudServiceName;
243
+ }
244
+ }
245
+ /**
246
+ * Apply changes to mta.yaml.
247
+ *
248
+ * @param cfConfig writer configuration
249
+ * @param mtaInstance MTA configuration instance
250
+ */
251
+ async function saveMta(cfConfig, mtaInstance) {
252
+ if (await mtaInstance.save()) {
253
+ // Add mtaext if required for API Hub Enterprise connectivity
254
+ if (cfConfig.apiHubConfig?.apiHubType === "API_HUB_ENTERPRISE" /* ApiHubType.apiHubEnterprise */) {
255
+ try {
256
+ await mtaInstance.addMtaExtensionConfig(cfConfig.destinationName, cfConfig.serviceHost, {
257
+ key: 'ApiKey',
258
+ value: cfConfig.apiHubConfig.apiHubKey
259
+ });
260
+ }
261
+ catch (error) {
262
+ logger_helper_1.default.logger?.error((0, i18n_1.t)('error.mtaExtensionFailed', { error }));
263
+ }
264
+ }
265
+ }
266
+ }
267
+ /**
268
+ * Appends the Cloud Foundry specific configurations to the project.
269
+ *
270
+ * @param cfConfig writer configuration
271
+ * @param fs reference to a mem-fs editor
272
+ */
273
+ async function appendCloudFoundryConfigurations(cfConfig, fs) {
274
+ // When data source is none in app generator, it is not required to provide destination
275
+ if (cfConfig.destinationName && cfConfig.destinationName !== constants_1.EmptyDestination) {
276
+ fs.copyTpl((0, utils_1.getTemplatePath)('app/xs-app-destination.json'), (0, path_1.join)(cfConfig.appPath, constants_1.XSAppFile), {
277
+ destination: cfConfig.destinationName,
278
+ servicePathSegment: `${cfConfig.firstServicePathSegment}${cfConfig.isFullUrlDest ? '/.*' : ''}`, // For service URL's, pull out everything after the last slash
279
+ targetPath: `${cfConfig.isFullUrlDest ? '' : cfConfig.firstServicePathSegment}/$1`, // Pull group 1 from the regex
280
+ authentication: cfConfig.destinationAuthType === constants_1.NoAuthType ? 'none' : 'xsuaa'
281
+ });
282
+ }
283
+ else {
284
+ fs.copyTpl((0, utils_1.getTemplatePath)('app/xs-app-no-destination.json'), (0, path_1.join)(cfConfig.appPath, constants_1.XSAppFile));
285
+ }
286
+ await generateUI5DeployConfig(cfConfig, fs);
287
+ }
288
+ /**
289
+ * Updates the manifest.json file with the cloud service name.
290
+ *
291
+ * @param cfConfig writer configuration
292
+ * @param fs reference to a mem-fs editor
293
+ */
294
+ async function updateManifest(cfConfig, fs) {
295
+ const manifest = await (0, utils_1.readManifest)((0, path_1.join)(cfConfig.appPath, 'webapp/manifest.json'), fs);
296
+ if (manifest && cfConfig.cloudServiceName) {
297
+ const sapCloud = {
298
+ ...(manifest['sap.cloud'] || {}),
299
+ public: true,
300
+ service: cfConfig.cloudServiceName
301
+ };
302
+ fs.extendJSON((0, path_1.join)(cfConfig.appPath, 'webapp/manifest.json'), {
303
+ 'sap.cloud': sapCloud
304
+ });
305
+ }
306
+ }
307
+ /**
308
+ * Updates the package.json file with the necessary scripts and dependencies.
309
+ *
310
+ * @param cfConfig writer configuration
311
+ * @param fs reference to a mem-fs editor
312
+ */
313
+ async function updateHTML5AppPackage(cfConfig, fs) {
314
+ let deployArgs = [];
315
+ if (fs.exists((0, path_1.join)(cfConfig.appPath, constants_1.MTAFileExtension))) {
316
+ deployArgs = ['-e', constants_1.MTAFileExtension];
317
+ }
318
+ await (0, project_access_1.updatePackageScript)(cfConfig.appPath, 'build:cf', constants_1.UI5DeployBuildScript, fs);
319
+ await (0, project_access_1.updatePackageScript)(cfConfig.appPath, 'build:mta', constants_1.MTABuildScript, fs);
320
+ await (0, project_access_1.updatePackageScript)(cfConfig.appPath, 'deploy', (0, constants_1.appDeployMTAScript)(deployArgs), fs);
321
+ await (0, project_access_1.updatePackageScript)(cfConfig.appPath, 'undeploy', (0, constants_1.undeployMTAScript)(cfConfig.mtaId ?? cfConfig.appId), fs);
322
+ await (0, utils_1.addCommonPackageDependencies)(cfConfig.appPath, fs);
323
+ }
324
+ /**
325
+ * Update the root package.json with scripts to deploy the MTA.
326
+ *
327
+ * @param cfConfig writer configuration
328
+ * @param fs reference to a mem-fs editor
329
+ */
330
+ async function updateRootPackage(cfConfig, fs) {
331
+ const packageExists = fs.exists((0, path_1.join)(cfConfig.rootPath, 'package.json'));
332
+ // Append mta scripts only if mta.yaml is a different level to the HTML5 app
333
+ if (cfConfig.isMtaRoot && packageExists) {
334
+ let deployArgs = [];
335
+ if (fs.exists((0, path_1.join)(cfConfig.rootPath, constants_1.MTAFileExtension))) {
336
+ deployArgs = ['-e', constants_1.MTAFileExtension];
337
+ }
338
+ [
339
+ { name: 'undeploy', run: (0, constants_1.undeployMTAScript)(cfConfig.mtaId ?? cfConfig.appId) },
340
+ { name: 'build', run: `${constants_1.MTABuildScript} --mtar archive` },
341
+ { name: 'deploy', run: (0, constants_1.rootDeployMTAScript)(deployArgs) }
342
+ ].forEach(async (script) => {
343
+ await (0, project_access_1.updatePackageScript)(cfConfig.rootPath, script.name, script.run, fs);
344
+ });
345
+ await (0, utils_1.addCommonPackageDependencies)(cfConfig.rootPath, fs);
346
+ }
347
+ }
348
+ /**
349
+ * Generate UI5 deploy config.
350
+ *
351
+ * @param cfConfig - the deploy config
352
+ * @param fs reference to a mem-fs editor
353
+ * @returns the deploy config
354
+ */
355
+ async function generateUI5DeployConfig(cfConfig, fs) {
356
+ const ui5BaseConfig = await (0, project_access_1.readUi5Yaml)(cfConfig.appPath, project_access_1.FileName.Ui5Yaml, fs);
357
+ const addTranspileTask = !!ui5BaseConfig.findCustomMiddleware('ui5-tooling-transpile-task');
358
+ const addModulesTask = !!ui5BaseConfig.findCustomMiddleware('ui5-tooling-modules-task');
359
+ const baseUi5Doc = ui5BaseConfig.removeConfig('server');
360
+ const ui5DeployConfig = await ui5_config_1.UI5Config.newInstance(baseUi5Doc.toString());
361
+ ui5DeployConfig.addComment({
362
+ comment: ' yaml-language-server: $schema=https://sap.github.io/ui5-tooling/schema/ui5.yaml.json',
363
+ location: 'beginning'
364
+ });
365
+ ui5DeployConfig.addCloudFoundryDeployTask(cfConfig.appId, addModulesTask, addTranspileTask);
366
+ fs.write((0, path_1.join)(cfConfig.appPath, project_access_1.FileName.UI5DeployYaml), ui5DeployConfig.toString());
367
+ }
368
+ //# sourceMappingURL=app-config.js.map