@sap-ux/app-config-writer 0.0.2

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.
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,57 @@
1
+ # @sap-ux/app-config-writer
2
+
3
+ The `@sap-ux/app-config-writer` adds or updates configurations to a SAP Fiori tools project.
4
+
5
+ ## Features
6
+
7
+ ### Smart Links configuration
8
+ You can define smart links in an application to provide navigation links to other SAP Fiori applications in a standardized way.
9
+ To be able to deliver an application with preconfigured targets for the included smart links, you need to import the available targets from a remote configuration of the SAP Fiori launchpad with the provided `add smart links config` command.
10
+ Then you can configure the smart links with the help of the preview mode for developer variant creation.
11
+ https://help.sap.com/docs/SAP_FIORI_tools/17d50220bcd848aa854c9c182d65b699/ceb845a45dd94f4c8bd52f2976f99090.html?q=developer%20variant%20creation&locale=en-US
12
+
13
+ ## Installation
14
+ Npm
15
+ `npm install --save @sap-ux/app-config-writer`
16
+
17
+ Yarn
18
+ `yarn add @sap-ux/app-config-writer`
19
+
20
+ Pnpm
21
+ `pnpm add @sap-ux/app-config-writer`
22
+
23
+ ## Usage
24
+
25
+ ### Smart Links configuration
26
+
27
+ #### Using @sap-ux/create module
28
+
29
+ - You can easily add a smart links configuration by running:
30
+ `npm init @sap-ux add smartlinks-config`
31
+
32
+ #### Using @sap-ux/app-config-writer
33
+ ```Typescript
34
+ import { generateSmartLinksConfig } from '@sap-ux/app-config-writer';
35
+
36
+ const myProjectPath = 'path/to/my/project'; // Path to the root of the Fiori app
37
+ const target = {
38
+ url: 'https://abc.example', // For BAS, use `destination`
39
+ client: '100', // Optional client
40
+ };
41
+ const auth = { username: 'user', password: 'password' }; // Authentication details
42
+
43
+ const exampleSmartLinksConfig = async () => {
44
+ const fs = await generateSmartLinksConfig(myProjectPath, { target, auth });
45
+ return new Promise((resolve) => {
46
+ fs.commit(resolve);
47
+ });
48
+ };
49
+
50
+ // Calling the function
51
+ exampleSmartLinksConfig();
52
+ ```
53
+
54
+ See more complex example in [`/test/unit`](./test/unit)
55
+
56
+ ## Keywords
57
+ SAP Fiori elements
package/dist/i18n.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ import type { TOptions } from 'i18next';
2
+ /**
3
+ * Initialize i18next with the translations for this module.
4
+ */
5
+ export declare function initI18n(): Promise<void>;
6
+ /**
7
+ * Helper function facading the call to i18next.
8
+ *
9
+ * @param key i18n key
10
+ * @param options additional options
11
+ * @returns {string} localized string stored for the given key
12
+ */
13
+ export declare function t(key: string, options?: TOptions): string;
14
+ //# sourceMappingURL=i18n.d.ts.map
package/dist/i18n.js ADDED
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.t = exports.initI18n = void 0;
16
+ const i18next_1 = __importDefault(require("i18next"));
17
+ const smartlinks_config_json_1 = __importDefault(require("./translations/smartlinks-config.json"));
18
+ const NS = 'app-config-writer';
19
+ /**
20
+ * Initialize i18next with the translations for this module.
21
+ */
22
+ function initI18n() {
23
+ return __awaiter(this, void 0, void 0, function* () {
24
+ yield i18next_1.default.init({
25
+ resources: {
26
+ en: {
27
+ [NS]: smartlinks_config_json_1.default
28
+ }
29
+ },
30
+ lng: 'en',
31
+ fallbackLng: 'en',
32
+ defaultNS: NS,
33
+ ns: [NS]
34
+ });
35
+ });
36
+ }
37
+ exports.initI18n = initI18n;
38
+ /**
39
+ * Helper function facading the call to i18next.
40
+ *
41
+ * @param key i18n key
42
+ * @param options additional options
43
+ * @returns {string} localized string stored for the given key
44
+ */
45
+ function t(key, options) {
46
+ return i18next_1.default.t(key, options);
47
+ }
48
+ exports.t = t;
49
+ initI18n();
50
+ //# sourceMappingURL=i18n.js.map
@@ -0,0 +1,3 @@
1
+ export { getSmartLinksTargetFromPrompt } from './prompt';
2
+ export { generateSmartLinksConfig } from './smartlinks-config';
3
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generateSmartLinksConfig = exports.getSmartLinksTargetFromPrompt = void 0;
4
+ var prompt_1 = require("./prompt");
5
+ Object.defineProperty(exports, "getSmartLinksTargetFromPrompt", { enumerable: true, get: function () { return prompt_1.getSmartLinksTargetFromPrompt; } });
6
+ var smartlinks_config_1 = require("./smartlinks-config");
7
+ Object.defineProperty(exports, "generateSmartLinksConfig", { enumerable: true, get: function () { return smartlinks_config_1.generateSmartLinksConfig; } });
8
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,2 @@
1
+ export { getSmartLinksTargetFromPrompt, promptUserPass } from './smartlinks-config';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.promptUserPass = exports.getSmartLinksTargetFromPrompt = void 0;
4
+ var smartlinks_config_1 = require("./smartlinks-config");
5
+ Object.defineProperty(exports, "getSmartLinksTargetFromPrompt", { enumerable: true, get: function () { return smartlinks_config_1.getSmartLinksTargetFromPrompt; } });
6
+ Object.defineProperty(exports, "promptUserPass", { enumerable: true, get: function () { return smartlinks_config_1.promptUserPass; } });
7
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,19 @@
1
+ import type { AxiosBasicCredentials } from 'axios';
2
+ import type { ToolsLogger } from '@sap-ux/logger';
3
+ import type { TargetConfig } from '../types';
4
+ /**
5
+ * Prompts the user for credentials.
6
+ *
7
+ * @param log logger to report info to the user
8
+ * @returns prompted user and password serialized for a basic auth header
9
+ */
10
+ export declare function promptUserPass(log?: ToolsLogger): Promise<AxiosBasicCredentials>;
11
+ /**
12
+ * Return the list of questions to configure smartlinks.
13
+ *
14
+ * @param basePath - path to project root, where ui5-deploy.yaml is
15
+ * @param logger logger to report info to the user
16
+ * @returns - array of questions that serves as input for prompt module
17
+ */
18
+ export declare function getSmartLinksTargetFromPrompt(basePath: string, logger?: ToolsLogger): Promise<TargetConfig>;
19
+ //# sourceMappingURL=smartlinks-config.d.ts.map
@@ -0,0 +1,224 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.getSmartLinksTargetFromPrompt = exports.promptUserPass = void 0;
13
+ const chalk_1 = require("chalk");
14
+ const prompts_1 = require("prompts");
15
+ const btp_utils_1 = require("@sap-ux/btp-utils");
16
+ const project_access_1 = require("@sap-ux/project-access");
17
+ const i18n_1 = require("../i18n");
18
+ const smartlinks_config_1 = require("../smartlinks-config");
19
+ const types_1 = require("../types");
20
+ /**
21
+ * Validator helper function for prompts.
22
+ *
23
+ * @param value entry to be verified
24
+ * @param error error message to be displayed
25
+ * @returns boolean or error message
26
+ */
27
+ const validator = (value, error) => {
28
+ if (!value || !value.trim()) {
29
+ return (0, i18n_1.t)(error);
30
+ }
31
+ else {
32
+ return true;
33
+ }
34
+ };
35
+ /**
36
+ * Questions specifically for app studio to be displayed.
37
+ *
38
+ * @param questions Prompt object array to be filled
39
+ * @param target deploy target definition
40
+ */
41
+ const addAppStudioQuestions = (questions, target) => {
42
+ // Offer existing configuration
43
+ if ((target === null || target === void 0 ? void 0 : target.destination) || (target === null || target === void 0 ? void 0 : target.url)) {
44
+ questions.push({
45
+ name: (target === null || target === void 0 ? void 0 : target.destination) ? types_1.TargetType.destination : types_1.TargetType.url,
46
+ message: (0, i18n_1.t)('questions.useTarget', { target: target.destination || target.url }),
47
+ type: 'confirm',
48
+ initial: true,
49
+ format: (confirm) => (confirm ? target.destination || target.url : confirm)
50
+ });
51
+ }
52
+ // Offer destination or url configuration
53
+ questions.push({
54
+ name: 'select',
55
+ type: (prev) => (!prev ? 'select' : null),
56
+ message: (0, i18n_1.t)('questions.target'),
57
+ choices: [
58
+ { title: (0, i18n_1.t)('questions.enter', { type: types_1.TargetType.destination }), value: types_1.TargetType.destination },
59
+ { title: (0, i18n_1.t)('questions.enter', { type: types_1.TargetType.url }), value: types_1.TargetType.url }
60
+ ]
61
+ });
62
+ // destination
63
+ questions.push({
64
+ type: (prev) => (prev === types_1.TargetType.destination ? 'text' : null),
65
+ name: types_1.TargetType.destination,
66
+ initial: target === null || target === void 0 ? void 0 : target.destination,
67
+ message: (0, i18n_1.t)('questions.target', {
68
+ type: types_1.TargetType.destination,
69
+ file: (target === null || target === void 0 ? void 0 : target.destination) ? `(${project_access_1.FileName.UI5DeployYaml})` : ''
70
+ }),
71
+ validate: (value) => validator(value, 'error.target')
72
+ });
73
+ };
74
+ /**
75
+ * Returns deploy questions for prompt.
76
+ *
77
+ * @param target deploy target definition
78
+ * @returns Prompt object array of questions
79
+ */
80
+ const getTargetPromptQuestions = (target) => {
81
+ const questions = [];
82
+ if ((0, btp_utils_1.isAppStudio)()) {
83
+ addAppStudioQuestions(questions, target);
84
+ }
85
+ // Offer url configuration for VSCode and BAS instance
86
+ questions.push({
87
+ type: (prev) => (!prev || prev === types_1.TargetType.url ? 'text' : null),
88
+ name: types_1.TargetType.url,
89
+ initial: target === null || target === void 0 ? void 0 : target.url,
90
+ message: (0, i18n_1.t)('questions.target', {
91
+ type: types_1.TargetType.url,
92
+ file: (target === null || target === void 0 ? void 0 : target.url) ? `(${project_access_1.FileName.UI5DeployYaml})` : ''
93
+ }),
94
+ validate: (value) => validator(value, 'error.target')
95
+ }, {
96
+ name: 'client',
97
+ type: (_prev, values) => ((values === null || values === void 0 ? void 0 : values.url) ? 'text' : null),
98
+ initial: target === null || target === void 0 ? void 0 : target.client,
99
+ message: (0, i18n_1.t)('questions.client', {
100
+ file: (target === null || target === void 0 ? void 0 : target.client) ? `(${project_access_1.FileName.UI5DeployYaml})` : ''
101
+ }),
102
+ format: (val) => (typeof val === 'number' ? val.toString() : val)
103
+ });
104
+ return questions;
105
+ };
106
+ /**
107
+ * Returns target parameters from prompt.
108
+ *
109
+ * @param config possible deploy config with target to be offered for prompt
110
+ * @param logger logger to report info to the user
111
+ * @returns target configuration
112
+ */
113
+ const getTargetPrompt = (config, logger) => __awaiter(void 0, void 0, void 0, function* () {
114
+ const cancel = {
115
+ onCancel: () => {
116
+ logger === null || logger === void 0 ? void 0 : logger.info((0, chalk_1.yellow)((0, i18n_1.t)('info.operationAborted')));
117
+ return process.exit(1);
118
+ }
119
+ };
120
+ const questions = getTargetPromptQuestions(config === null || config === void 0 ? void 0 : config.target);
121
+ const { url, client, destination } = yield (0, prompts_1.prompt)(questions, cancel);
122
+ return { url, client, destination };
123
+ });
124
+ /**
125
+ * Prompts the user for credentials.
126
+ *
127
+ * @param log logger to report info to the user
128
+ * @returns prompted user and password serialized for a basic auth header
129
+ */
130
+ function promptUserPass(log) {
131
+ return __awaiter(this, void 0, void 0, function* () {
132
+ const { username, password } = yield (0, prompts_1.prompt)([
133
+ {
134
+ type: 'text',
135
+ name: 'username',
136
+ message: `${(0, chalk_1.cyan)((0, i18n_1.t)('info.username'))}`,
137
+ validate: (value) => {
138
+ if (!value || !value.trim()) {
139
+ return `${(0, i18n_1.t)('error.emptyUsername')}`;
140
+ }
141
+ else {
142
+ return true;
143
+ }
144
+ }
145
+ },
146
+ {
147
+ type: 'invisible',
148
+ name: 'password',
149
+ message: `${(0, chalk_1.cyan)((0, i18n_1.t)('info.password'))}`,
150
+ validate: (value) => {
151
+ if (!value || !value.trim()) {
152
+ return `${(0, i18n_1.t)('error.emptyPassword')}`;
153
+ }
154
+ else {
155
+ return true;
156
+ }
157
+ }
158
+ }
159
+ ], {
160
+ onCancel: () => {
161
+ log === null || log === void 0 ? void 0 : log.info((0, chalk_1.yellow)((0, i18n_1.t)('info.operationAborted')));
162
+ return process.exit(1);
163
+ }
164
+ });
165
+ return { username, password };
166
+ });
167
+ }
168
+ exports.promptUserPass = promptUserPass;
169
+ /**
170
+ * Returns credentials from target or from prompt.
171
+ *
172
+ * @param target target definition to be checked for existing credentials
173
+ * @param logger logger to report info to the user
174
+ * @returns credentials for target definition
175
+ */
176
+ function getCredentialsPrompt(target, logger) {
177
+ return __awaiter(this, void 0, void 0, function* () {
178
+ if ((0, btp_utils_1.isAppStudio)() && target.destination) {
179
+ const destinations = yield (0, btp_utils_1.listDestinations)();
180
+ const destination = destinations === null || destinations === void 0 ? void 0 : destinations[target.destination];
181
+ if ((destination === null || destination === void 0 ? void 0 : destination.Authentication) === 'NoAuthentication') {
182
+ logger === null || logger === void 0 ? void 0 : logger.info((0, i18n_1.t)('info.credentialsRequired'));
183
+ return yield promptUserPass(logger);
184
+ }
185
+ else if (destination) {
186
+ logger === null || logger === void 0 ? void 0 : logger.info((0, i18n_1.t)('info.credentialsAvailable'));
187
+ return undefined;
188
+ }
189
+ }
190
+ else if (target.url) {
191
+ const auth = yield (0, smartlinks_config_1.getLocalStoredCredentials)(target.url, target.client, logger);
192
+ if (auth === null || auth === void 0 ? void 0 : auth.username) {
193
+ const choices = [
194
+ { title: `Use ${auth.username}`, value: auth },
195
+ { title: (0, i18n_1.t)('questions.credentialsDescription'), value: false }
196
+ ];
197
+ const { credentials } = yield (0, prompts_1.prompt)([
198
+ { name: 'credentials', type: 'select', message: (0, i18n_1.t)('questions.credentials'), choices, initial: 0 }
199
+ ]);
200
+ if (credentials) {
201
+ return credentials;
202
+ }
203
+ }
204
+ }
205
+ return promptUserPass(logger);
206
+ });
207
+ }
208
+ /**
209
+ * Return the list of questions to configure smartlinks.
210
+ *
211
+ * @param basePath - path to project root, where ui5-deploy.yaml is
212
+ * @param logger logger to report info to the user
213
+ * @returns - array of questions that serves as input for prompt module
214
+ */
215
+ function getSmartLinksTargetFromPrompt(basePath, logger) {
216
+ return __awaiter(this, void 0, void 0, function* () {
217
+ const definition = yield (0, smartlinks_config_1.getTargetDefinition)(basePath, logger);
218
+ const target = yield getTargetPrompt(definition, logger);
219
+ const auth = yield getCredentialsPrompt(target, logger);
220
+ return { target, auth, ignoreCertErrors: definition === null || definition === void 0 ? void 0 : definition.ignoreCertErrors };
221
+ });
222
+ }
223
+ exports.getSmartLinksTargetFromPrompt = getSmartLinksTargetFromPrompt;
224
+ //# sourceMappingURL=smartlinks-config.js.map
@@ -0,0 +1,14 @@
1
+ import type { Editor } from 'mem-fs-editor';
2
+ import type { ToolsLogger } from '@sap-ux/logger';
3
+ import type { TargetConfig } from '../types';
4
+ /**
5
+ * Add smartlinks configuration to a UI5 application.
6
+ *
7
+ * @param basePath - the base path where the ui5-deploy/ui5.yaml is
8
+ * @param config - configuration of the target system for smartlinks
9
+ * @param logger - logger
10
+ * @param fs - the memfs editor instance
11
+ * @returns Promise<Editor> - memfs editor instance with updated files
12
+ */
13
+ export declare function generateSmartLinksConfig(basePath: string, config: TargetConfig, logger?: ToolsLogger, fs?: Editor): Promise<Editor>;
14
+ //# sourceMappingURL=generateSmartLinks.d.ts.map
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.generateSmartLinksConfig = void 0;
13
+ const mem_fs_1 = require("mem-fs");
14
+ const mem_fs_editor_1 = require("mem-fs-editor");
15
+ const utils_1 = require("./utils");
16
+ /**
17
+ * Add smartlinks configuration to a UI5 application.
18
+ *
19
+ * @param basePath - the base path where the ui5-deploy/ui5.yaml is
20
+ * @param config - configuration of the target system for smartlinks
21
+ * @param logger - logger
22
+ * @param fs - the memfs editor instance
23
+ * @returns Promise<Editor> - memfs editor instance with updated files
24
+ */
25
+ function generateSmartLinksConfig(basePath, config, logger, fs) {
26
+ return __awaiter(this, void 0, void 0, function* () {
27
+ if (!fs) {
28
+ fs = (0, mem_fs_editor_1.create)((0, mem_fs_1.create)());
29
+ }
30
+ yield (0, utils_1.writeSmartLinksConfig)(basePath, config, fs, logger);
31
+ return fs;
32
+ });
33
+ }
34
+ exports.generateSmartLinksConfig = generateSmartLinksConfig;
35
+ //# sourceMappingURL=generateSmartLinks.js.map
@@ -0,0 +1,3 @@
1
+ export * from './generateSmartLinks';
2
+ export { getTargetDefinition, getLocalStoredCredentials } from './utils';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.getLocalStoredCredentials = exports.getTargetDefinition = void 0;
18
+ __exportStar(require("./generateSmartLinks"), exports);
19
+ var utils_1 = require("./utils");
20
+ Object.defineProperty(exports, "getTargetDefinition", { enumerable: true, get: function () { return utils_1.getTargetDefinition; } });
21
+ Object.defineProperty(exports, "getLocalStoredCredentials", { enumerable: true, get: function () { return utils_1.getLocalStoredCredentials; } });
22
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,19 @@
1
+ import type { Editor } from 'mem-fs-editor';
2
+ import type { ToolsLogger } from '@sap-ux/logger';
3
+ import type { TargetConfig } from '../types';
4
+ /**
5
+ * Reads and returns target information from ui5-deploy.yaml, if existing.
6
+ *
7
+ * @param basePath - path to project root, where ui5-deploy.yaml is
8
+ * @returns {TargetConfig} target definition for deploy configuration
9
+ */
10
+ export declare function readUi5DeployConfigTarget(basePath: string): Promise<TargetConfig>;
11
+ /**
12
+ * Reads and adds servestatic configuration to ui5/-local/-mock.yaml files.
13
+ *
14
+ * @param basePath - path to project root, where ui5.yaml is
15
+ * @param fs - mem-fs reference to be used for file access
16
+ * @param logger - logger
17
+ */
18
+ export declare function addUi5YamlServeStaticMiddleware(basePath: string, fs: Editor, logger?: ToolsLogger): Promise<void>;
19
+ //# sourceMappingURL=ui5-yaml.d.ts.map
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.addUi5YamlServeStaticMiddleware = exports.readUi5DeployConfigTarget = void 0;
13
+ const path_1 = require("path");
14
+ const project_access_1 = require("@sap-ux/project-access");
15
+ const i18n_1 = require("../i18n");
16
+ const types_1 = require("../types");
17
+ /**
18
+ * Reads and returns target information from ui5-deploy.yaml, if existing.
19
+ *
20
+ * @param basePath - path to project root, where ui5-deploy.yaml is
21
+ * @returns {TargetConfig} target definition for deploy configuration
22
+ */
23
+ function readUi5DeployConfigTarget(basePath) {
24
+ var _a;
25
+ return __awaiter(this, void 0, void 0, function* () {
26
+ const ui5DeployYaml = yield (0, project_access_1.readUi5Yaml)(basePath, project_access_1.FileName.UI5DeployYaml);
27
+ const customTask = ui5DeployYaml.findCustomTask(types_1.DeployConfig.DeployToAbap);
28
+ if (!((_a = customTask === null || customTask === void 0 ? void 0 : customTask.configuration) === null || _a === void 0 ? void 0 : _a.target)) {
29
+ throw Error((0, i18n_1.t)('error.noTarget', { file: `(${project_access_1.FileName.UI5DeployYaml})` }));
30
+ }
31
+ const { target, ignoreCertError } = customTask === null || customTask === void 0 ? void 0 : customTask.configuration;
32
+ return { target, ignoreCertErrors: ignoreCertError };
33
+ });
34
+ }
35
+ exports.readUi5DeployConfigTarget = readUi5DeployConfigTarget;
36
+ /**
37
+ * Checks if 'fiori-tools-servestatic' configuration is already existing.
38
+ *
39
+ * @param existingPaths existing configuration paths under 'fiori-tools-servestatic'
40
+ * @param existingFioriToolsProxy - flag if fiori tools proxy middleware is already existing
41
+ * @returns 'fiori-tools-servestatic' configuration, if not existing yet
42
+ */
43
+ const getFioriToolsServeStaticMiddlewareConfig = (existingPaths, existingFioriToolsProxy) => {
44
+ const configPath = { path: '/appconfig', src: 'appconfig', fallthrough: false };
45
+ if (existingPaths.find((existing) => existing.path === configPath.path && existing.src === configPath.src)) {
46
+ return undefined;
47
+ }
48
+ const paths = [...existingPaths, configPath];
49
+ const beforeAfterMiddleware = existingFioriToolsProxy
50
+ ? { beforeMiddleware: 'fiori-tools-proxy' }
51
+ : { afterMiddleware: 'compression' };
52
+ return Object.assign(Object.assign({ name: 'fiori-tools-servestatic' }, beforeAfterMiddleware), { configuration: { paths } });
53
+ };
54
+ /**
55
+ * Reads and adds servestatic configuration to ui5/-local/-mock.yaml files.
56
+ *
57
+ * @param basePath - path to project root, where ui5.yaml is
58
+ * @param fs - mem-fs reference to be used for file access
59
+ * @param logger - logger
60
+ */
61
+ function addUi5YamlServeStaticMiddleware(basePath, fs, logger) {
62
+ return __awaiter(this, void 0, void 0, function* () {
63
+ const ui5Yamls = [project_access_1.FileName.Ui5Yaml, project_access_1.FileName.Ui5MockYaml, project_access_1.FileName.Ui5LocalYaml];
64
+ for (const ui5Yaml of ui5Yamls) {
65
+ let ui5YamlConfig;
66
+ try {
67
+ ui5YamlConfig = yield (0, project_access_1.readUi5Yaml)(basePath, ui5Yaml);
68
+ }
69
+ catch (error) {
70
+ logger === null || logger === void 0 ? void 0 : logger.debug(`File ${ui5Yaml} not existing`);
71
+ continue;
72
+ }
73
+ const existingFioriToolsProxy = !!ui5YamlConfig.findCustomMiddleware(types_1.DeployConfig.FioriToolsProxy);
74
+ const appServeStaticMiddleware = ui5YamlConfig.findCustomMiddleware(types_1.DeployConfig.FioriToolsServestatic);
75
+ const middleware = getFioriToolsServeStaticMiddlewareConfig((appServeStaticMiddleware === null || appServeStaticMiddleware === void 0 ? void 0 : appServeStaticMiddleware.configuration.paths) || [], existingFioriToolsProxy);
76
+ if (middleware) {
77
+ const yamlConfig = ui5YamlConfig.updateCustomMiddleware(middleware);
78
+ const yaml = yamlConfig.toString();
79
+ fs.write((0, path_1.join)(basePath, ui5Yaml), yaml);
80
+ }
81
+ }
82
+ });
83
+ }
84
+ exports.addUi5YamlServeStaticMiddleware = addUi5YamlServeStaticMiddleware;
85
+ //# sourceMappingURL=ui5-yaml.js.map
@@ -0,0 +1,47 @@
1
+ import type { AxiosBasicCredentials } from 'axios';
2
+ import type { Editor } from 'mem-fs-editor';
3
+ import type { ToolsLogger } from '@sap-ux/logger';
4
+ import type { InboundTargetsConfig, SystemDetailsResponse, TargetConfig } from '../types';
5
+ /**
6
+ * Check the secure storage if it has credentials for the entered url.
7
+ *
8
+ * @param url target system url
9
+ * @param client optional sap-client parameter
10
+ * @param logger Logger for user output
11
+ * @returns credentials or undefined
12
+ */
13
+ export declare function getLocalStoredCredentials(url: string, client?: string, logger?: ToolsLogger): Promise<AxiosBasicCredentials | undefined>;
14
+ /**
15
+ * Sends a request to a target and returns the result.
16
+ *
17
+ * @param config target and credentials to be used for request
18
+ * @param logger logger to report info to the user
19
+ * @returns response from service provider
20
+ */
21
+ export declare function sendRequest(config: TargetConfig, logger?: ToolsLogger): Promise<SystemDetailsResponse>;
22
+ /**
23
+ * Get target definition of deploy system as source for smartlinks configuration.
24
+ *
25
+ * @param basePath - path to project root, where ui5-deploy.yaml is
26
+ * @param logger - logger
27
+ * @returns target definition
28
+ */
29
+ export declare function getTargetDefinition(basePath: string, logger?: ToolsLogger): Promise<TargetConfig | undefined>;
30
+ /**
31
+ * Receives and maps targets from service to template for further consumption.
32
+ *
33
+ * @param config service and credentials to be used for request
34
+ * @param logger logger
35
+ * @returns config with targets to be used for template mapping
36
+ */
37
+ export declare function getTargetMappingsConfig(config: TargetConfig, logger?: ToolsLogger): Promise<InboundTargetsConfig>;
38
+ /**
39
+ * Add or enhance appconfig smartlinks configuration.
40
+ *
41
+ * @param basePath - the base path of the application
42
+ * @param config - configuration of the target system for smartlinks
43
+ * @param fs - the memfs editor instance
44
+ * @param logger - logger
45
+ */
46
+ export declare function writeSmartLinksConfig(basePath: string, config: TargetConfig, fs: Editor, logger?: ToolsLogger): Promise<void>;
47
+ //# sourceMappingURL=utils.d.ts.map
@@ -0,0 +1,217 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.writeSmartLinksConfig = exports.getTargetMappingsConfig = exports.getTargetDefinition = exports.sendRequest = exports.getLocalStoredCredentials = void 0;
13
+ const chalk_1 = require("chalk");
14
+ const ejs_1 = require("ejs");
15
+ const path_1 = require("path");
16
+ const axios_extension_1 = require("@sap-ux/axios-extension");
17
+ const btp_utils_1 = require("@sap-ux/btp-utils");
18
+ const project_access_1 = require("@sap-ux/project-access");
19
+ const store_1 = require("@sap-ux/store");
20
+ const i18n_1 = require("../i18n");
21
+ const templates_1 = require("../templates");
22
+ const ui5_yaml_1 = require("./ui5-yaml");
23
+ /**
24
+ * URL parameters for call to backend
25
+ */
26
+ const UrlParameters = {
27
+ so: '*',
28
+ action: '*',
29
+ systemAliasesFormat: 'object',
30
+ 'sap-language': 'EN',
31
+ shellType: 'FLP',
32
+ depth: 0
33
+ };
34
+ /**
35
+ * Check the secure storage if it has credentials for the entered url.
36
+ *
37
+ * @param url target system url
38
+ * @param client optional sap-client parameter
39
+ * @param logger Logger for user output
40
+ * @returns credentials or undefined
41
+ */
42
+ function getLocalStoredCredentials(url, client, logger) {
43
+ return __awaiter(this, void 0, void 0, function* () {
44
+ // check if system credentials are stored in the store
45
+ try {
46
+ const systemStore = yield (0, store_1.getService)({ logger, entityName: 'system' });
47
+ const system = yield systemStore.read(new store_1.BackendSystemKey({ url, client }));
48
+ return (system === null || system === void 0 ? void 0 : system.username) ? { username: system.username, password: system.password || '' } : undefined;
49
+ }
50
+ catch (error) {
51
+ logger === null || logger === void 0 ? void 0 : logger.warn((0, i18n_1.t)('warnings.useCredentialsFailed'));
52
+ logger === null || logger === void 0 ? void 0 : logger.debug(error);
53
+ }
54
+ return undefined;
55
+ });
56
+ }
57
+ exports.getLocalStoredCredentials = getLocalStoredCredentials;
58
+ /**
59
+ * Creates and returns a service provider.
60
+ *
61
+ * @param config configuration with target, authentication and ignoreCertErrors flag
62
+ * @returns service provider
63
+ */
64
+ function createSmartLinksProvider(config) {
65
+ const { target, auth, ignoreCertErrors } = config;
66
+ let provider;
67
+ if ((0, btp_utils_1.isAppStudio)() && target.destination) {
68
+ provider = (0, axios_extension_1.createForDestination)({ auth }, { Name: target.destination });
69
+ delete provider.defaults.params['saml2'];
70
+ }
71
+ else {
72
+ provider = (0, axios_extension_1.createForAbap)({
73
+ baseURL: target.url,
74
+ auth,
75
+ ignoreCertErrors,
76
+ params: target.client ? { 'sap-client': target.client } : undefined
77
+ });
78
+ }
79
+ return provider;
80
+ }
81
+ /**
82
+ * Sends a request to a target and returns the result.
83
+ *
84
+ * @param config target and credentials to be used for request
85
+ * @param logger logger to report info to the user
86
+ * @returns response from service provider
87
+ */
88
+ function sendRequest(config, logger) {
89
+ return __awaiter(this, void 0, void 0, function* () {
90
+ const target = (0, btp_utils_1.isAppStudio)() && config.target.destination ? config.target.destination : config.target.url;
91
+ if (!target) {
92
+ throw Error((0, i18n_1.t)('error.target'));
93
+ }
94
+ try {
95
+ const provider = createSmartLinksProvider(config);
96
+ logger === null || logger === void 0 ? void 0 : logger.info(`${(0, chalk_1.cyan)((0, i18n_1.t)('info.connectTo'))} ${target}`);
97
+ const response = yield provider.get('/sap/bc/ui2/start_up', { params: UrlParameters });
98
+ logger === null || logger === void 0 ? void 0 : logger.info((0, chalk_1.cyan)((0, i18n_1.t)('info.connectSuccess')));
99
+ return JSON.parse(response.data);
100
+ }
101
+ catch (error) {
102
+ logger === null || logger === void 0 ? void 0 : logger.debug(error);
103
+ throw Error(error.message);
104
+ }
105
+ });
106
+ }
107
+ exports.sendRequest = sendRequest;
108
+ /**
109
+ * Get target definition of deploy system as source for smartlinks configuration.
110
+ *
111
+ * @param basePath - path to project root, where ui5-deploy.yaml is
112
+ * @param logger - logger
113
+ * @returns target definition
114
+ */
115
+ function getTargetDefinition(basePath, logger) {
116
+ return __awaiter(this, void 0, void 0, function* () {
117
+ logger === null || logger === void 0 ? void 0 : logger.info((0, i18n_1.t)('info.searchTarget', { file: project_access_1.FileName.UI5DeployYaml }));
118
+ try {
119
+ const target = yield (0, ui5_yaml_1.readUi5DeployConfigTarget)(basePath);
120
+ logger === null || logger === void 0 ? void 0 : logger.info((0, chalk_1.cyan)((0, i18n_1.t)('info.targetFound', { file: project_access_1.FileName.UI5DeployYaml })));
121
+ return target;
122
+ }
123
+ catch (err) {
124
+ logger === null || logger === void 0 ? void 0 : logger.warn(err.message);
125
+ logger === null || logger === void 0 ? void 0 : logger.debug(err);
126
+ return undefined;
127
+ }
128
+ });
129
+ }
130
+ exports.getTargetDefinition = getTargetDefinition;
131
+ /**
132
+ * Sends a request and returns the target mappings.
133
+ *
134
+ * @param config service and credentials to be used for request
135
+ * @param logger logger
136
+ * @returns target mappings result from service
137
+ */
138
+ function getTargetMappings(config, logger) {
139
+ return __awaiter(this, void 0, void 0, function* () {
140
+ const response = yield sendRequest(config, logger);
141
+ if (!response || !response.targetMappings) {
142
+ throw Error((0, i18n_1.t)('error.noTarget'));
143
+ }
144
+ return response.targetMappings;
145
+ });
146
+ }
147
+ /**
148
+ * Receives and maps targets from service to template for further consumption.
149
+ *
150
+ * @param config service and credentials to be used for request
151
+ * @param logger logger
152
+ * @returns config with targets to be used for template mapping
153
+ */
154
+ function getTargetMappingsConfig(config, logger) {
155
+ return __awaiter(this, void 0, void 0, function* () {
156
+ const targetMappings = yield getTargetMappings(config, logger);
157
+ const inboundConfig = {};
158
+ for (const targetName in targetMappings) {
159
+ const target = targetMappings[targetName];
160
+ inboundConfig[targetName] = {
161
+ semanticObject: target.semanticObject,
162
+ action: target.semanticAction,
163
+ title: target.text,
164
+ signature: Object.assign({ additionalParameters: 'ignored', parameters: {} }, target.signature),
165
+ resolutionResult: {}
166
+ };
167
+ }
168
+ return inboundConfig;
169
+ });
170
+ }
171
+ exports.getTargetMappingsConfig = getTargetMappingsConfig;
172
+ /**
173
+ * Maps service targets to existing targets in appconfig sandboxConfig file.
174
+ *
175
+ * @param appConfigPath path to apps appconfig/fioriSandboxConfig.json file
176
+ * @param inboundTargets returned targets from service
177
+ * @param fs - the memfs editor instance
178
+ * @returns merged inbound targets
179
+ */
180
+ function mergeTargetMappings(appConfigPath, inboundTargets, fs) {
181
+ var _a, _b, _c, _d;
182
+ const existingConfig = fs.readJSON(appConfigPath);
183
+ const existingTargets = (_d = (_c = (_b = (_a = existingConfig.services) === null || _a === void 0 ? void 0 : _a.ClientSideTargetResolution) === null || _b === void 0 ? void 0 : _b.adapter) === null || _c === void 0 ? void 0 : _c.config) === null || _d === void 0 ? void 0 : _d.inbounds;
184
+ if (existingTargets) {
185
+ Object.entries(inboundTargets).forEach(([name, value]) => {
186
+ existingTargets[name] = value;
187
+ });
188
+ return existingTargets;
189
+ }
190
+ return inboundTargets;
191
+ }
192
+ /**
193
+ * Add or enhance appconfig smartlinks configuration.
194
+ *
195
+ * @param basePath - the base path of the application
196
+ * @param config - configuration of the target system for smartlinks
197
+ * @param fs - the memfs editor instance
198
+ * @param logger - logger
199
+ */
200
+ function writeSmartLinksConfig(basePath, config, fs, logger) {
201
+ return __awaiter(this, void 0, void 0, function* () {
202
+ let inboundTargets = yield getTargetMappingsConfig(config, logger);
203
+ const templatePath = (0, templates_1.getTemplatePath)('smartlinks-config/fioriSandboxConfig.json');
204
+ const appConfigPath = (0, path_1.join)(basePath, 'appconfig', 'fioriSandboxConfig.json');
205
+ if (!fs.exists(appConfigPath)) {
206
+ fs.copyTpl(templatePath, appConfigPath, { inboundTargets });
207
+ }
208
+ else {
209
+ inboundTargets = mergeTargetMappings(appConfigPath, inboundTargets, fs);
210
+ const filledTemplate = (0, ejs_1.render)(fs.read(templatePath), { inboundTargets }, {});
211
+ fs.extendJSON(appConfigPath, JSON.parse(filledTemplate));
212
+ }
213
+ yield (0, ui5_yaml_1.addUi5YamlServeStaticMiddleware)(basePath, fs, logger);
214
+ });
215
+ }
216
+ exports.writeSmartLinksConfig = writeSmartLinksConfig;
217
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Locates template files relative to the dist folder.
3
+ * This helps to locate templates when this module is bundled and the dir structure is flattened, maintaining the relative paths.
4
+ *
5
+ * @param relativeTemplatePath - optional, the path of the required template relative to the ./templates folder. If not specified the root templates folder is returned.
6
+ * @returns the path of the template specified or templates root folder
7
+ */
8
+ export declare function getTemplatePath(relativeTemplatePath?: string): string;
9
+ //# sourceMappingURL=templates.d.ts.map
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getTemplatePath = void 0;
4
+ const path_1 = require("path");
5
+ /**
6
+ * Locates template files relative to the dist folder.
7
+ * This helps to locate templates when this module is bundled and the dir structure is flattened, maintaining the relative paths.
8
+ *
9
+ * @param relativeTemplatePath - optional, the path of the required template relative to the ./templates folder. If not specified the root templates folder is returned.
10
+ * @returns the path of the template specified or templates root folder
11
+ */
12
+ function getTemplatePath(relativeTemplatePath = '') {
13
+ return (0, path_1.join)(__dirname, '../templates', relativeTemplatePath);
14
+ }
15
+ exports.getTemplatePath = getTemplatePath;
16
+ //# sourceMappingURL=templates.js.map
@@ -0,0 +1,31 @@
1
+ {
2
+ "questions": {
3
+ "enter": "Enter {{-type}}",
4
+ "useTarget": "Do you want to use {{-target}}",
5
+ "target": "SmartLinks configuration source {{-type}} {{-file}}",
6
+ "client": "SAP client {{-file}}",
7
+ "credentials": "Credentials to be used",
8
+ "credentialsDescription": "Provide username and password"
9
+ },
10
+ "warnings": {
11
+ "useCredentialsFailed": "Retrieving stored credentials failed."
12
+ },
13
+ "info": {
14
+ "username": "Username",
15
+ "password": "Password",
16
+ "searchTarget": "Searching for deploy target definition {{-file}}",
17
+ "targetFound": "Deploy target definition found {{-file}}",
18
+ "credentialsAvailable": "Credentials taken from stored system",
19
+ "credentialsRequired": "Credentials are required. Please enter your credentials below",
20
+ "authNeeded": "Credentials might be required. Do you want to enter your credentials?",
21
+ "operationAborted": "Operation aborted by the user.",
22
+ "connectTo": "Connecting to",
23
+ "connectSuccess": "Connection successful"
24
+ },
25
+ "error": {
26
+ "target": "Please provide a target for configuration",
27
+ "noTarget": "No target definition found {{-file}}",
28
+ "emptyUsername": "Username can not be empty.",
29
+ "emptyPassword": "Password can not be empty."
30
+ }
31
+ }
@@ -0,0 +1,2 @@
1
+ export * from './smartLinks';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./smartLinks"), exports);
18
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,69 @@
1
+ import type { AxiosBasicCredentials } from 'axios';
2
+ import type { AbapTarget } from '@sap-ux/ui5-config';
3
+ export declare enum DeployConfig {
4
+ 'DeployToAbap' = "deploy-to-abap",
5
+ 'FioriToolsProxy' = "fiori-tools-proxy",
6
+ 'FioriToolsServestatic' = "fiori-tools-servestatic"
7
+ }
8
+ export declare enum TargetType {
9
+ destination = "destination",
10
+ url = "url"
11
+ }
12
+ export type DeployTarget = Pick<AbapTarget, 'url' | 'client' | 'destination' | 'scp'>;
13
+ /**
14
+ * Configuration of a target system.
15
+ */
16
+ export interface TargetConfig {
17
+ target: DeployTarget;
18
+ ignoreCertErrors?: boolean;
19
+ auth?: AxiosBasicCredentials;
20
+ }
21
+ export type TargetMapping = {
22
+ applicationType?: string;
23
+ formFactors?: {
24
+ [key: string]: boolean;
25
+ };
26
+ semanticAction: string;
27
+ semanticObject: string;
28
+ signature: {
29
+ additionalParameters?: string;
30
+ parameters?: {
31
+ [key: string]: any;
32
+ };
33
+ };
34
+ text?: string;
35
+ url?: string;
36
+ };
37
+ export type SystemDetailsResponse = {
38
+ systemAlias?: object;
39
+ targetMappings?: {
40
+ [key: string]: TargetMapping;
41
+ };
42
+ urlTemplates?: object;
43
+ version?: string;
44
+ };
45
+ export type InboundTarget = {
46
+ action: string;
47
+ semanticObject: string;
48
+ signature: {
49
+ parameters: object;
50
+ additionalParameters: string;
51
+ };
52
+ title?: string;
53
+ resolutionResult?: {};
54
+ };
55
+ export type InboundTargetsConfig = {
56
+ [key: string]: InboundTarget;
57
+ };
58
+ export type SmartLinksSandboxConfig = {
59
+ services?: {
60
+ ClientSideTargetResolution?: {
61
+ adapter?: {
62
+ config?: {
63
+ inbounds?: InboundTargetsConfig;
64
+ };
65
+ };
66
+ };
67
+ };
68
+ };
69
+ //# sourceMappingURL=smartLinks.d.ts.map
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TargetType = exports.DeployConfig = void 0;
4
+ var DeployConfig;
5
+ (function (DeployConfig) {
6
+ DeployConfig["DeployToAbap"] = "deploy-to-abap";
7
+ DeployConfig["FioriToolsProxy"] = "fiori-tools-proxy";
8
+ DeployConfig["FioriToolsServestatic"] = "fiori-tools-servestatic";
9
+ })(DeployConfig = exports.DeployConfig || (exports.DeployConfig = {}));
10
+ var TargetType;
11
+ (function (TargetType) {
12
+ TargetType["destination"] = "destination";
13
+ TargetType["url"] = "url";
14
+ })(TargetType = exports.TargetType || (exports.TargetType = {}));
15
+ //# sourceMappingURL=smartLinks.js.map
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@sap-ux/app-config-writer",
3
+ "description": "Add or update configuration for SAP Fiori tools application",
4
+ "version": "0.0.2",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "https://github.com/SAP/open-ux-tools.git",
8
+ "directory": "packages/app-config-writer"
9
+ },
10
+ "bugs": {
11
+ "url": "https://github.com/SAP/open-ux-tools/issues?q=is%3Aopen+is%3Aissue+label%3Abug+label%app-config-writer"
12
+ },
13
+ "license": "Apache-2.0",
14
+ "main": "dist/index.js",
15
+ "files": [
16
+ "LICENSE",
17
+ "dist",
18
+ "templates",
19
+ "!dist/*.map",
20
+ "!dist/**/*.map"
21
+ ],
22
+ "dependencies": {
23
+ "@sap-ux/axios-extension": "1.0.3",
24
+ "@sap-ux/btp-utils": "0.11.5",
25
+ "@sap-ux/logger": "0.3.5",
26
+ "@sap-ux/project-access": "1.3.0",
27
+ "@sap-ux/store": "0.3.10",
28
+ "@sap-ux/ui5-config": "0.16.5",
29
+ "chalk": "4.1.2",
30
+ "ejs": "3.1.7",
31
+ "i18next": "20.3.2",
32
+ "mem-fs": "2.1.0",
33
+ "mem-fs-editor": "9.4.0",
34
+ "prompts": "2.4.2"
35
+ },
36
+ "devDependencies": {
37
+ "@types/ejs": "3.1.0",
38
+ "@types/mem-fs": "1.1.2",
39
+ "@types/mem-fs-editor": "7.0.1",
40
+ "@types/prompts": "2.0.14",
41
+ "axios": "0.24.0",
42
+ "nock": "13.2.1"
43
+ },
44
+ "engines": {
45
+ "pnpm": ">=6.26.1 < 7.0.0 || >=7.1.0",
46
+ "node": ">= 14.16.0 < 15.0.0 || >=16.1.0 < 17.0.0 || >=18.0.0 < 19.0.0"
47
+ },
48
+ "scripts": {
49
+ "build": "tsc --build",
50
+ "watch": "tsc --watch",
51
+ "clean": "rimraf dist coverage *.tsbuildinfo",
52
+ "format": "prettier --write '**/*.{js,json,ts,yaml,yml}' --ignore-path ../../.prettierignore",
53
+ "lint": "eslint . --ext .ts",
54
+ "lint:fix": "eslint . --ext .ts --fix",
55
+ "test": "jest --ci --forceExit --detectOpenHandles --colors"
56
+ }
57
+ }
@@ -0,0 +1,13 @@
1
+ {
2
+ "services": {
3
+ "ClientSideTargetResolution": {
4
+ "adapter": {
5
+ "config": {
6
+ "inbounds": { <% Object.keys(locals.inboundTargets).forEach((target, index) => { %>
7
+ "<%- target %>": <%- JSON.stringify(locals.inboundTargets[target], null, '\t') %><% if( index < Object.keys(locals.inboundTargets).length -1 ){ %>, <% } %><% }) %>
8
+ }
9
+ }
10
+ }
11
+ }
12
+ }
13
+ }