@sap-ux/mockserver-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,33 @@
1
+ # @sap-ux/mockserver-config-writer
2
+
3
+ Adds or removes configuration for mockserver module `@sap-ux/ui5-middleware-fe-mockserver` to SAP UX project.
4
+
5
+ ## Installation
6
+ Npm
7
+ `npm install --save @sap-ux/mockserver-config-writer`
8
+
9
+ Yarn
10
+ `yarn add @sap-ux/mockserver-config-writer`
11
+
12
+ Pnpm
13
+ `pnpm add @sap-ux/mockserver-config-writer`
14
+
15
+ ## Usage
16
+ ```Typescript
17
+ import { generateMockserverConfig } from '@sap-ux/mockserver-config-writer';
18
+ import { join } from 'path';
19
+
20
+ const basePath = join(__dirname, 'test/fixtures/bare-minimum');
21
+ const fs = await generateMockserverConfig(
22
+ basePath,
23
+ {
24
+ webappPath: join(basePath, 'webapp'),
25
+ });
26
+
27
+ fs.commit();
28
+ ```
29
+
30
+ See more complex example in [`/test/unit`](./test/unit)
31
+ ## Keywords
32
+ SAP Fiori elements
33
+ SAP Fiori - UI5 middleware for the Fiori elements mock server
@@ -0,0 +1,18 @@
1
+ import type { Manifest, ManifestNamespace } from '@sap-ux/project-access';
2
+ /**
3
+ * Get the main service data source entry from manifest.json.
4
+ *
5
+ * @param manifest - Parsed manifest.json
6
+ * @returns - data source entry from manifest.json, parsed
7
+ */
8
+ export declare function getMainServiceDataSource(manifest: Manifest): ManifestNamespace.DataSource | undefined;
9
+ /**
10
+ * Get the data sources of type 'OData' from manifest.
11
+ *
12
+ * @param manifest - the parsed manifest.json
13
+ * @returns data sources of type 'OData'
14
+ */
15
+ export declare function getODataSources(manifest: Manifest): {
16
+ [k: string]: ManifestNamespace.DataSource;
17
+ };
18
+ //# sourceMappingURL=app-info.d.ts.map
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getODataSources = exports.getMainServiceDataSource = void 0;
4
+ /**
5
+ * Get the main service data source entry from manifest.json.
6
+ *
7
+ * @param manifest - Parsed manifest.json
8
+ * @returns - data source entry from manifest.json, parsed
9
+ */
10
+ function getMainServiceDataSource(manifest) {
11
+ var _a, _b;
12
+ let dataSource;
13
+ const model = ((_a = manifest['sap.ovp']) === null || _a === void 0 ? void 0 : _a.globalFilterModel) || '';
14
+ const dataSourceName = manifest['sap.ui5'] && manifest['sap.ui5'].models && manifest['sap.ui5'].models[model]
15
+ ? manifest['sap.ui5'].models[model].dataSource
16
+ : undefined;
17
+ if (dataSourceName) {
18
+ dataSource = (_b = manifest['sap.app'].dataSources) === null || _b === void 0 ? void 0 : _b[dataSourceName];
19
+ }
20
+ return dataSource;
21
+ }
22
+ exports.getMainServiceDataSource = getMainServiceDataSource;
23
+ /**
24
+ * Get the data sources of type 'OData' from manifest.
25
+ *
26
+ * @param manifest - the parsed manifest.json
27
+ * @returns data sources of type 'OData'
28
+ */
29
+ function getODataSources(manifest) {
30
+ var _a;
31
+ const result = {};
32
+ const dataSources = ((_a = manifest['sap.app']) === null || _a === void 0 ? void 0 : _a.dataSources) || {};
33
+ for (const dataSource in dataSources) {
34
+ if (dataSources[dataSource].uri && dataSources[dataSource].type === 'OData') {
35
+ result[dataSource] = dataSources[dataSource];
36
+ }
37
+ }
38
+ return result;
39
+ }
40
+ exports.getODataSources = getODataSources;
41
+ //# sourceMappingURL=app-info.js.map
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 mockserver_config_writer_i18n_json_1 = __importDefault(require("./translations/mockserver-config-writer.i18n.json"));
18
+ const NS = 'odata-service-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]: mockserver_config_writer_i18n_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,5 @@
1
+ export { generateMockserverConfig, removeMockserverConfig } from './mockserver-config';
2
+ export { getMockserverConfigQuestions } from './prompt';
3
+ export { t } from './i18n';
4
+ export * from './types';
5
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -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
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
10
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11
+ };
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.t = exports.getMockserverConfigQuestions = exports.removeMockserverConfig = exports.generateMockserverConfig = void 0;
14
+ var mockserver_config_1 = require("./mockserver-config");
15
+ Object.defineProperty(exports, "generateMockserverConfig", { enumerable: true, get: function () { return mockserver_config_1.generateMockserverConfig; } });
16
+ Object.defineProperty(exports, "removeMockserverConfig", { enumerable: true, get: function () { return mockserver_config_1.removeMockserverConfig; } });
17
+ var prompt_1 = require("./prompt");
18
+ Object.defineProperty(exports, "getMockserverConfigQuestions", { enumerable: true, get: function () { return prompt_1.getMockserverConfigQuestions; } });
19
+ var i18n_1 = require("./i18n");
20
+ Object.defineProperty(exports, "t", { enumerable: true, get: function () { return i18n_1.t; } });
21
+ __exportStar(require("./types"), exports);
22
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,20 @@
1
+ import type { Editor } from 'mem-fs-editor';
2
+ import type { MockserverConfig } from '../types';
3
+ /**
4
+ * Add mockserver configuration to a UI5 application.
5
+ *
6
+ * @param basePath - the base path where the package.json and ui5.yaml is
7
+ * @param data - configuration of the mockserver
8
+ * @param fs - the memfs editor instance
9
+ * @returns Promise<Editor> - memfs editor instance with updated files
10
+ */
11
+ export declare function generateMockserverConfig(basePath: string, data: MockserverConfig, fs?: Editor): Promise<Editor>;
12
+ /**
13
+ * Remove mockserver configuration.
14
+ *
15
+ * @param basePath - the base path where the package.json and ui5.yaml is
16
+ * @param fs - the memfs editor instance
17
+ * @returns Promise<Editor> - memfs editor instance with updated files
18
+ */
19
+ export declare function removeMockserverConfig(basePath: string, fs?: Editor): Editor;
20
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,52 @@
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.removeMockserverConfig = exports.generateMockserverConfig = void 0;
13
+ const mem_fs_1 = require("mem-fs");
14
+ const mem_fs_editor_1 = require("mem-fs-editor");
15
+ const package_json_1 = require("./package-json");
16
+ const ui5_mock_yaml_1 = require("./ui5-mock-yaml");
17
+ /**
18
+ * Add mockserver configuration to a UI5 application.
19
+ *
20
+ * @param basePath - the base path where the package.json and ui5.yaml is
21
+ * @param data - configuration of the mockserver
22
+ * @param fs - the memfs editor instance
23
+ * @returns Promise<Editor> - memfs editor instance with updated files
24
+ */
25
+ function generateMockserverConfig(basePath, data, fs) {
26
+ return __awaiter(this, void 0, void 0, function* () {
27
+ if (!fs) {
28
+ fs = mem_fs_editor_1.create(mem_fs_1.create());
29
+ }
30
+ package_json_1.enhancePackageJson(fs, basePath, data.packageJsonConfig);
31
+ yield ui5_mock_yaml_1.enhanceYaml(fs, basePath, data.webappPath, data.ui5MockYamlConfig);
32
+ return fs;
33
+ });
34
+ }
35
+ exports.generateMockserverConfig = generateMockserverConfig;
36
+ /**
37
+ * Remove mockserver configuration.
38
+ *
39
+ * @param basePath - the base path where the package.json and ui5.yaml is
40
+ * @param fs - the memfs editor instance
41
+ * @returns Promise<Editor> - memfs editor instance with updated files
42
+ */
43
+ function removeMockserverConfig(basePath, fs) {
44
+ if (!fs) {
45
+ fs = mem_fs_editor_1.create(mem_fs_1.create());
46
+ }
47
+ package_json_1.removeFromPackageJson(fs, basePath);
48
+ ui5_mock_yaml_1.removeUi5MockYaml(fs, basePath);
49
+ return fs;
50
+ }
51
+ exports.removeMockserverConfig = removeMockserverConfig;
52
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,18 @@
1
+ import type { Editor } from 'mem-fs-editor';
2
+ import type { PackageJsonMockConfig } from '../types';
3
+ /**
4
+ * Enhance the package.json with dependency for mockserver.
5
+ *
6
+ * @param fs - mem-fs reference to be used for file access
7
+ * @param basePath - path to application root, where package.json is
8
+ * @param config - optional config for mockserver
9
+ */
10
+ export declare function enhancePackageJson(fs: Editor, basePath: string, config?: PackageJsonMockConfig): void;
11
+ /**
12
+ * Remove mockserver script and dependencies from package.json.
13
+ *
14
+ * @param fs - mem-fs reference to be used for file access
15
+ * @param basePath - path to application root, where package.json is
16
+ */
17
+ export declare function removeFromPackageJson(fs: Editor, basePath: string): void;
18
+ //# sourceMappingURL=package-json.d.ts.map
@@ -0,0 +1,126 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.removeFromPackageJson = exports.enhancePackageJson = void 0;
4
+ const path_1 = require("path");
5
+ /**
6
+ * Enhance the package.json with dependency for mockserver.
7
+ *
8
+ * @param fs - mem-fs reference to be used for file access
9
+ * @param basePath - path to application root, where package.json is
10
+ * @param config - optional config for mockserver
11
+ */
12
+ function enhancePackageJson(fs, basePath, config) {
13
+ const packageJsonPath = path_1.join(basePath, 'package.json');
14
+ const packageJson = fs.readJSON(packageJsonPath);
15
+ enhanceDependencies(packageJson, config === null || config === void 0 ? void 0 : config.mockserverModule, config === null || config === void 0 ? void 0 : config.mockserverVersion);
16
+ enhanceScripts(fs, packageJson);
17
+ fs.writeJSON(packageJsonPath, packageJson);
18
+ }
19
+ exports.enhancePackageJson = enhancePackageJson;
20
+ /**
21
+ * Add mockserver dependencies to package.json content.
22
+ * Takes also care of removing deprecated old module.
23
+ *
24
+ * @param packageJson - parsed package.json content
25
+ * @param mockserverModule - npm name of the mockserver module
26
+ * @param version - npm version string
27
+ */
28
+ function enhanceDependencies(packageJson, mockserverModule = '@sap-ux/ui5-middleware-fe-mockserver', version = '2') {
29
+ var _a;
30
+ packageJson.devDependencies = packageJson.devDependencies || {};
31
+ delete packageJson.devDependencies['@sap/ux-ui5-fe-mockserver-middleware'];
32
+ packageJson.devDependencies[mockserverModule] = version;
33
+ packageJson.ui5 || (packageJson.ui5 = {});
34
+ (_a = packageJson.ui5).dependencies || (_a.dependencies = []);
35
+ const ui5Dependencies = packageJson.ui5.dependencies.filter((dep) => dep !== '@sap/ux-ui5-fe-mockserver-middleware');
36
+ if (!ui5Dependencies.includes(mockserverModule)) {
37
+ ui5Dependencies.push(mockserverModule);
38
+ }
39
+ packageJson.ui5.dependencies = ui5Dependencies;
40
+ }
41
+ /**
42
+ * Add or update start-mock script to package.json.
43
+ *
44
+ * @param fs - mem-fs reference to be used for file access
45
+ * @param packageJson - path to package.json
46
+ */
47
+ function enhanceScripts(fs, packageJson) {
48
+ packageJson.scripts || (packageJson.scripts = {});
49
+ packageJson.scripts['start-mock'] =
50
+ copyStartScript(packageJson.scripts.start) || `fiori run --config ./ui5-mock.yaml --open \"/\"`;
51
+ }
52
+ /**
53
+ * Return a copy of package.json's 'start' script with added or replaced config pointing to ui5-mock.yaml.
54
+ * In case start script can't be copied or is undefined, return undefined.
55
+ *
56
+ * @param startScript - start script from package.json
57
+ * @returns - copy of start script with config to ui5.yaml, undefined if start script can't be copied
58
+ */
59
+ function copyStartScript(startScript) {
60
+ if (typeof startScript !== 'string') {
61
+ return undefined;
62
+ }
63
+ const fioriRun = 'fiori run';
64
+ const fioriRunIndex = startScript.indexOf(fioriRun);
65
+ if (fioriRunIndex < 0) {
66
+ return undefined;
67
+ }
68
+ const configStartIndex = startScript.indexOf('--config', fioriRunIndex);
69
+ const startMockScript = configStartIndex < 0
70
+ ? startScript.replace(fioriRun, `${fioriRun} --config ./ui5-mock.yaml`)
71
+ : replaceConfig(startScript, configStartIndex);
72
+ return startMockScript;
73
+ }
74
+ /**
75
+ * Replace the --config <any/path> in script with --config ./ui5-mock.yaml and return as new string.
76
+ *
77
+ * @param startScript - script that contains --config path/to/any.yaml
78
+ * @param configStartIndex - index in string where --config starts (first after fiori run)
79
+ * @returns - new script string with replaced --config
80
+ */
81
+ function replaceConfig(startScript, configStartIndex) {
82
+ const argStart = configStartIndex + '--config'.length + 1;
83
+ const yamlStart = startScript.slice(argStart).search(/[^\s]/) + argStart;
84
+ let separator = ' ';
85
+ let quotischSepOffset = 0;
86
+ if (startScript[yamlStart] === '"' || startScript[yamlStart] === "'") {
87
+ separator = startScript[yamlStart];
88
+ quotischSepOffset = 1;
89
+ }
90
+ let yamlEnd = startScript.indexOf(separator, yamlStart + quotischSepOffset);
91
+ yamlEnd = yamlEnd === -1 ? startScript.length : yamlEnd + quotischSepOffset;
92
+ const startMockScript = `${startScript.substring(0, argStart)}./ui5-mock.yaml${startScript.substring(yamlEnd)}`;
93
+ return startMockScript;
94
+ }
95
+ /**
96
+ * Remove mockserver script and dependencies from package.json.
97
+ *
98
+ * @param fs - mem-fs reference to be used for file access
99
+ * @param basePath - path to application root, where package.json is
100
+ */
101
+ function removeFromPackageJson(fs, basePath) {
102
+ var _a, _b, _c, _d;
103
+ const packageJsonPath = path_1.join(basePath, 'package.json');
104
+ const packageJson = fs.readJSON(packageJsonPath);
105
+ (_a = packageJson.scripts) === null || _a === void 0 ? true : delete _a['start-mock'];
106
+ if (packageJson.scripts && Object.keys(packageJson.scripts).length === 0) {
107
+ delete packageJson.scripts;
108
+ }
109
+ (_b = packageJson.devDependencies) === null || _b === void 0 ? true : delete _b['@sap/ux-ui5-fe-mockserver-middleware'];
110
+ (_c = packageJson.devDependencies) === null || _c === void 0 ? true : delete _c['@sap-ux/ui5-middleware-fe-mockserver'];
111
+ if (packageJson.devDependencies && Object.keys(packageJson.devDependencies).length === 0) {
112
+ delete packageJson.devDependencies;
113
+ }
114
+ if (((_d = packageJson.ui5) === null || _d === void 0 ? void 0 : _d.dependencies) && Array.isArray(packageJson.ui5.dependencies)) {
115
+ packageJson.ui5.dependencies = packageJson.ui5.dependencies.filter((d) => d !== '@sap/ux-ui5-fe-mockserver-middleware' && d !== '@sap-ux/ui5-middleware-fe-mockserver');
116
+ if (packageJson.ui5.dependencies.length === 0) {
117
+ delete packageJson.ui5.dependencies;
118
+ }
119
+ }
120
+ if (packageJson.ui5 && Object.keys(packageJson.ui5).length === 0) {
121
+ delete packageJson.ui5;
122
+ }
123
+ fs.writeJSON(packageJsonPath, packageJson);
124
+ }
125
+ exports.removeFromPackageJson = removeFromPackageJson;
126
+ //# sourceMappingURL=package-json.js.map
@@ -0,0 +1,31 @@
1
+ import type { Editor } from 'mem-fs-editor';
2
+ import type { Ui5MockYamlConfig } from '../types';
3
+ /**
4
+ * Enhance or create the ui5-mock.yaml with mockserver config.
5
+ * Following enhancement strategy is applied:
6
+ *
7
+ * ui5-mock.yaml exists
8
+ * -----------------------------
9
+ * Update or create middleware configuration for 'sap-fe-mockserver' with the latest configuration.
10
+ * Other parts of the ui5-mock.yaml will not be modified.
11
+ *
12
+ * ui5-mock.yaml does not exist
13
+ * -----------------------------
14
+ * If ui5.yaml exists, copy it and add/update the 'sap-fe-mockserver' middleware configuration.
15
+ * If ui5.yaml does not exist, create a new ui5-mock.yaml file with 'sap-fe-mockserver' middleware
16
+ * configuration and basic default configuration for 'fiori-tools-proxy' and 'fiori-tools-appreload'.
17
+ *
18
+ * @param fs - mem-fs reference to be used for file access
19
+ * @param basePath - path to project root, where package.json and ui5.yaml is
20
+ * @param webappPath - path to webapp folder, where manifest.json is
21
+ * @param config - optional config passed in by consumer
22
+ */
23
+ export declare function enhanceYaml(fs: Editor, basePath: string, webappPath: string, config?: Ui5MockYamlConfig): Promise<void>;
24
+ /**
25
+ * Delete ui5-mock.yaml file from mem-fs.
26
+ *
27
+ * @param fs - mem-fs reference to be used for file access
28
+ * @param basePath - path to project root, where package.json and ui5.yaml is
29
+ */
30
+ export declare function removeUi5MockYaml(fs: Editor, basePath: string): void;
31
+ //# sourceMappingURL=ui5-mock-yaml.d.ts.map
@@ -0,0 +1,132 @@
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.removeUi5MockYaml = exports.enhanceYaml = void 0;
13
+ const path_1 = require("path");
14
+ const ui5_config_1 = require("@sap-ux/ui5-config");
15
+ const app_info_1 = require("../app-info");
16
+ /**
17
+ * Enhance or create the ui5-mock.yaml with mockserver config.
18
+ * Following enhancement strategy is applied:
19
+ *
20
+ * ui5-mock.yaml exists
21
+ * -----------------------------
22
+ * Update or create middleware configuration for 'sap-fe-mockserver' with the latest configuration.
23
+ * Other parts of the ui5-mock.yaml will not be modified.
24
+ *
25
+ * ui5-mock.yaml does not exist
26
+ * -----------------------------
27
+ * If ui5.yaml exists, copy it and add/update the 'sap-fe-mockserver' middleware configuration.
28
+ * If ui5.yaml does not exist, create a new ui5-mock.yaml file with 'sap-fe-mockserver' middleware
29
+ * configuration and basic default configuration for 'fiori-tools-proxy' and 'fiori-tools-appreload'.
30
+ *
31
+ * @param fs - mem-fs reference to be used for file access
32
+ * @param basePath - path to project root, where package.json and ui5.yaml is
33
+ * @param webappPath - path to webapp folder, where manifest.json is
34
+ * @param config - optional config passed in by consumer
35
+ */
36
+ function enhanceYaml(fs, basePath, webappPath, config) {
37
+ var _a, _b;
38
+ return __awaiter(this, void 0, void 0, function* () {
39
+ const ui5MockYamlPath = path_1.join(basePath, 'ui5-mock.yaml');
40
+ let mockConfig;
41
+ const manifest = fs.readJSON(path_1.join(webappPath, 'manifest.json'));
42
+ const mockserverPath = (config === null || config === void 0 ? void 0 : config.path) || ((_a = app_info_1.getMainServiceDataSource(manifest)) === null || _a === void 0 ? void 0 : _a.uri);
43
+ if (fs.exists(ui5MockYamlPath)) {
44
+ mockConfig = yield updateUi5MockYamlConfig(fs, ui5MockYamlPath, mockserverPath);
45
+ }
46
+ else {
47
+ mockConfig = fs.exists(path_1.join(basePath, 'ui5.yaml'))
48
+ ? yield generateUi5MockYamlBasedOnUi5Yaml(fs, basePath, mockserverPath)
49
+ : yield generateNewUi5MockYamlConfig(((_b = manifest['sap.app']) === null || _b === void 0 ? void 0 : _b.id) || '', mockserverPath);
50
+ }
51
+ const yaml = mockConfig.toString();
52
+ fs.write(ui5MockYamlPath, yaml);
53
+ });
54
+ }
55
+ exports.enhanceYaml = enhanceYaml;
56
+ /**
57
+ * Update existing ui5-mock.yaml config. This will add or replace existing middleware configuration
58
+ * 'sap-fe-mockserver' with state of the art config.
59
+ *
60
+ * @param fs - Editor instance to read existing information
61
+ * @param ui5MockYamlPath - path to ui5-mock.yaml file
62
+ * @param [path] - optional url path the mockserver listens to
63
+ */
64
+ function updateUi5MockYamlConfig(fs, ui5MockYamlPath, path) {
65
+ return __awaiter(this, void 0, void 0, function* () {
66
+ const existingUi5MockYamlConfig = yield ui5_config_1.UI5Config.newInstance(fs.read(ui5MockYamlPath));
67
+ existingUi5MockYamlConfig.updateCustomMiddleware(yield getNewMockserverMiddleware(path));
68
+ return existingUi5MockYamlConfig;
69
+ });
70
+ }
71
+ /**
72
+ * Create a new ui5-mock.yaml based on existing ui5.yaml.
73
+ *
74
+ * @param fs - Editor instance to read existing information
75
+ * @param basePath -
76
+ * @param [path] - optional path for mockserver config
77
+ */
78
+ function generateUi5MockYamlBasedOnUi5Yaml(fs, basePath, path) {
79
+ return __awaiter(this, void 0, void 0, function* () {
80
+ const ui5MockYamlConfig = yield ui5_config_1.UI5Config.newInstance(fs.read(path_1.join(basePath, 'ui5.yaml')));
81
+ ui5MockYamlConfig.updateCustomMiddleware(yield getNewMockserverMiddleware(path));
82
+ return ui5MockYamlConfig;
83
+ });
84
+ }
85
+ /**
86
+ * Create fresh ui5-mock.yaml configuration which can be stringified and written.
87
+ *
88
+ * @param appId - application id
89
+ * @param [path] - optional url path the mockserver listens to
90
+ */
91
+ function generateNewUi5MockYamlConfig(appId, path) {
92
+ return __awaiter(this, void 0, void 0, function* () {
93
+ const ui5MockYaml = yield ui5_config_1.UI5Config.newInstance('# yaml-language-server: $schema=https://sap.github.io/ui5-tooling/schema/ui5.yaml.json\n\nspecVersion: "2.5"');
94
+ ui5MockYaml.setMetadata({ name: appId });
95
+ ui5MockYaml.setType('application');
96
+ ui5MockYaml.addFioriToolsProxydMiddleware({ ui5: {} });
97
+ ui5MockYaml.addFioriToolsAppReloadMiddleware();
98
+ ui5MockYaml.addMockServerMiddleware(path);
99
+ return ui5MockYaml;
100
+ });
101
+ }
102
+ /**
103
+ * Return new mockserver middleware.
104
+ *
105
+ * @param [path] - optional path for mockserver config
106
+ * @returns - mockserver middleware
107
+ */
108
+ function getNewMockserverMiddleware(path) {
109
+ return __awaiter(this, void 0, void 0, function* () {
110
+ const ui5MockYaml = yield ui5_config_1.UI5Config.newInstance('');
111
+ ui5MockYaml.addMockServerMiddleware(path);
112
+ const mockserverMiddleware = ui5MockYaml.findCustomMiddleware('sap-fe-mockserver');
113
+ if (!mockserverMiddleware) {
114
+ throw Error('Could not create new mockserver config');
115
+ }
116
+ return mockserverMiddleware;
117
+ });
118
+ }
119
+ /**
120
+ * Delete ui5-mock.yaml file from mem-fs.
121
+ *
122
+ * @param fs - mem-fs reference to be used for file access
123
+ * @param basePath - path to project root, where package.json and ui5.yaml is
124
+ */
125
+ function removeUi5MockYaml(fs, basePath) {
126
+ const ui5MockYamlPath = path_1.join(basePath, 'ui5-mock.yaml');
127
+ if (fs.exists(ui5MockYamlPath)) {
128
+ fs.delete(ui5MockYamlPath);
129
+ }
130
+ }
131
+ exports.removeUi5MockYaml = removeUi5MockYaml;
132
+ //# sourceMappingURL=ui5-mock-yaml.js.map
@@ -0,0 +1,15 @@
1
+ import type { Editor } from 'mem-fs-editor';
2
+ import type { PromptObject } from 'prompts';
3
+ /**
4
+ * Return the list of questions to configure mockserver.
5
+ *
6
+ * @param params - optional parameters used to fill default values
7
+ * @param params.webappPath - optional path to webapp folder, where manifest is
8
+ * @param params.fs - optional memfs editor instance
9
+ * @returns - array of questions that serves as input for prompt module
10
+ */
11
+ export declare function getMockserverConfigQuestions(params?: {
12
+ webappPath?: string;
13
+ fs?: Editor;
14
+ }): PromptObject[];
15
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getMockserverConfigQuestions = void 0;
4
+ const path_1 = require("path");
5
+ const mem_fs_1 = require("mem-fs");
6
+ const mem_fs_editor_1 = require("mem-fs-editor");
7
+ const app_info_1 = require("../app-info");
8
+ const __1 = require("..");
9
+ /**
10
+ * Return the list of questions to configure mockserver.
11
+ *
12
+ * @param params - optional parameters used to fill default values
13
+ * @param params.webappPath - optional path to webapp folder, where manifest is
14
+ * @param params.fs - optional memfs editor instance
15
+ * @returns - array of questions that serves as input for prompt module
16
+ */
17
+ function getMockserverConfigQuestions(params) {
18
+ var _a, _b;
19
+ const question = {
20
+ name: 'path',
21
+ message: __1.t('questions.pathToMock')
22
+ };
23
+ if (params === null || params === void 0 ? void 0 : params.webappPath) {
24
+ const fs = params.fs || mem_fs_editor_1.create(mem_fs_1.create());
25
+ const manifest = JSON.parse(fs.read(path_1.join(params.webappPath, 'manifest.json')));
26
+ const mainDataSourceUri = ((_a = app_info_1.getMainServiceDataSource(manifest)) === null || _a === void 0 ? void 0 : _a.uri) || '';
27
+ const oDataSources = app_info_1.getODataSources(manifest);
28
+ const choices = [];
29
+ for (const dsName in oDataSources) {
30
+ choices.push({
31
+ title: `${dsName}: ${oDataSources[dsName].uri}`,
32
+ value: oDataSources[dsName].uri,
33
+ description: ((_b = oDataSources[dsName].settings) === null || _b === void 0 ? void 0 : _b.odataVersion) || undefined
34
+ });
35
+ }
36
+ if (choices.length > 0) {
37
+ question.type = 'select';
38
+ question.choices = choices;
39
+ question.initial = choices.findIndex((c) => c.value === mainDataSourceUri);
40
+ }
41
+ }
42
+ question.type || (question.type = 'text');
43
+ return [question];
44
+ }
45
+ exports.getMockserverConfigQuestions = getMockserverConfigQuestions;
46
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,5 @@
1
+ {
2
+ "questions": {
3
+ "pathToMock": "Path to mocked service"
4
+ }
5
+ }
@@ -0,0 +1,14 @@
1
+ export interface MockserverConfig {
2
+ webappPath: string;
3
+ packageJsonConfig?: PackageJsonMockConfig;
4
+ ui5MockYamlConfig?: Ui5MockYamlConfig;
5
+ }
6
+ export interface PackageJsonMockConfig {
7
+ script?: string;
8
+ mockserverModule?: string;
9
+ mockserverVersion?: string;
10
+ }
11
+ export interface Ui5MockYamlConfig {
12
+ path?: string;
13
+ }
14
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=index.js.map
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@sap-ux/mockserver-config-writer",
3
+ "description": "Add or update configuration for SAP Fiori tools mockserver",
4
+ "version": "0.0.2",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "https://github.com/SAP/open-ux-tools.git",
8
+ "directory": "packages/mockserver-config-writer"
9
+ },
10
+ "bugs": {
11
+ "url": "https://github.com/SAP/open-ux-tools/issues?q=is%3Aopen+is%3Aissue+label%3Abug+label%3Amockserver-config-writer"
12
+ },
13
+ "license": "Apache-2.0",
14
+ "main": "dist/index.js",
15
+ "files": [
16
+ "LICENSE",
17
+ "dist",
18
+ "!dist/*.map",
19
+ "!dist/**/*.map"
20
+ ],
21
+ "dependencies": {
22
+ "@sap-ux/ui5-config": "0.16.1",
23
+ "i18next": "20.3.2",
24
+ "mem-fs": "2.1.0",
25
+ "mem-fs-editor": "9.4.0"
26
+ },
27
+ "devDependencies": {
28
+ "@sap-ux/project-access": "1.0.4",
29
+ "@types/mem-fs": "1.1.2",
30
+ "@types/mem-fs-editor": "7.0.1",
31
+ "@types/prompts": "2.0.14",
32
+ "prompts": "2.4.2"
33
+ },
34
+ "engines": {
35
+ "pnpm": ">=6.26.1 < 7.0.0 || >=7.1.0",
36
+ "node": ">= 14.16.0 < 15.0.0 || >=16.1.0 < 17.0.0 || >=18.0.0 < 19.0.0"
37
+ },
38
+ "scripts": {
39
+ "build": "tsc --build",
40
+ "clean": "rimraf dist coverage *.tsbuildinfo",
41
+ "format": "prettier --write '**/*.{js,json,ts,yaml,yml}' --ignore-path ../../.prettierignore",
42
+ "lint": "eslint . --ext .ts",
43
+ "lint:fix": "eslint . --ext .ts --fix",
44
+ "test": "jest --ci --forceExit --detectOpenHandles --colors",
45
+ "watch": "tsc --watch"
46
+ }
47
+ }