@itentialopensource/adapter-cisco_ise 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (226) hide show
  1. package/.eslintignore +5 -0
  2. package/.eslintrc.js +18 -0
  3. package/.jshintrc +3 -0
  4. package/AUTH.md +34 -0
  5. package/BROKER.md +211 -0
  6. package/CALLS.md +2991 -0
  7. package/CODE_OF_CONDUCT.md +43 -0
  8. package/CONTRIBUTING.md +13 -0
  9. package/ENHANCE.md +69 -0
  10. package/LICENSE +201 -0
  11. package/PROPERTIES.md +646 -0
  12. package/README.md +349 -0
  13. package/SUMMARY.md +9 -0
  14. package/SYSTEMINFO.md +23 -0
  15. package/TAB1.md +13 -0
  16. package/TAB2.md +306 -0
  17. package/TROUBLESHOOT.md +56 -0
  18. package/adapter.js +53480 -0
  19. package/adapterBase.js +1452 -0
  20. package/entities/.generic/action.json +214 -0
  21. package/entities/.generic/schema.json +28 -0
  22. package/entities/.system/action.json +50 -0
  23. package/entities/.system/mockdatafiles/getToken-default.json +3 -0
  24. package/entities/.system/mockdatafiles/healthcheck-default.json +3 -0
  25. package/entities/.system/schema.json +19 -0
  26. package/entities/.system/schemaTokenReq.json +53 -0
  27. package/entities/.system/schemaTokenResp.json +53 -0
  28. package/entities/ACIConnection/action.json +330 -0
  29. package/entities/ACIConnection/schema.json +34 -0
  30. package/entities/ACIData/action.json +205 -0
  31. package/entities/ACIData/schema.json +28 -0
  32. package/entities/ADGroups/action.json +25 -0
  33. package/entities/ADGroups/schema.json +19 -0
  34. package/entities/ActiveDirectories/action.json +25 -0
  35. package/entities/ActiveDirectories/schema.json +19 -0
  36. package/entities/BackupAndRestore/action.json +125 -0
  37. package/entities/BackupAndRestore/schema.json +24 -0
  38. package/entities/Certificates/action.json +452 -0
  39. package/entities/Certificates/schema.json +40 -0
  40. package/entities/ClassificationRule/action.json +146 -0
  41. package/entities/ClassificationRule/schema.json +25 -0
  42. package/entities/Configuration/action.json +24 -0
  43. package/entities/Configuration/schema.json +19 -0
  44. package/entities/CustomAttributes/action.json +106 -0
  45. package/entities/CustomAttributes/schema.json +23 -0
  46. package/entities/DataconnectServices/action.json +106 -0
  47. package/entities/DataconnectServices/schema.json +23 -0
  48. package/entities/DeviceAdminMFARules/action.json +126 -0
  49. package/entities/DeviceAdminMFARules/schema.json +24 -0
  50. package/entities/DeviceAdministrationAuthenticationRules/action.json +126 -0
  51. package/entities/DeviceAdministrationAuthenticationRules/schema.json +24 -0
  52. package/entities/DeviceAdministrationAuthorizationExceptionRules/action.json +126 -0
  53. package/entities/DeviceAdministrationAuthorizationExceptionRules/schema.json +24 -0
  54. package/entities/DeviceAdministrationAuthorizationGlobalExceptionRules/action.json +126 -0
  55. package/entities/DeviceAdministrationAuthorizationGlobalExceptionRules/schema.json +24 -0
  56. package/entities/DeviceAdministrationAuthorizationRules/action.json +126 -0
  57. package/entities/DeviceAdministrationAuthorizationRules/schema.json +24 -0
  58. package/entities/DeviceAdministrationCommandSets/action.json +25 -0
  59. package/entities/DeviceAdministrationCommandSets/schema.json +19 -0
  60. package/entities/DeviceAdministrationConditions/action.json +230 -0
  61. package/entities/DeviceAdministrationConditions/schema.json +29 -0
  62. package/entities/DeviceAdministrationDictionaryAttributesList/action.json +67 -0
  63. package/entities/DeviceAdministrationDictionaryAttributesList/schema.json +21 -0
  64. package/entities/DeviceAdministrationIdentityStores/action.json +25 -0
  65. package/entities/DeviceAdministrationIdentityStores/schema.json +19 -0
  66. package/entities/DeviceAdministrationNetworkConditions/action.json +106 -0
  67. package/entities/DeviceAdministrationNetworkConditions/schema.json +23 -0
  68. package/entities/DeviceAdministrationPolicySets/action.json +126 -0
  69. package/entities/DeviceAdministrationPolicySets/schema.json +24 -0
  70. package/entities/DeviceAdministrationServiceNames/action.json +25 -0
  71. package/entities/DeviceAdministrationServiceNames/schema.json +19 -0
  72. package/entities/DeviceAdministrationShellProfiles/action.json +25 -0
  73. package/entities/DeviceAdministrationShellProfiles/schema.json +19 -0
  74. package/entities/DeviceAdministrationTimeDateConditions/action.json +106 -0
  75. package/entities/DeviceAdministrationTimeDateConditions/schema.json +23 -0
  76. package/entities/DuoIdentitySync/action.json +168 -0
  77. package/entities/DuoIdentitySync/schema.json +26 -0
  78. package/entities/DuoMfa/action.json +147 -0
  79. package/entities/DuoMfa/schema.json +25 -0
  80. package/entities/EnableMFA/action.json +24 -0
  81. package/entities/EnableMFA/schema.json +19 -0
  82. package/entities/EndpointStopReplicationService/action.json +45 -0
  83. package/entities/EndpointStopReplicationService/schema.json +20 -0
  84. package/entities/Endpoints/action.json +207 -0
  85. package/entities/Endpoints/schema.json +28 -0
  86. package/entities/ExternalConnection/action.json +25 -0
  87. package/entities/ExternalConnection/schema.json +19 -0
  88. package/entities/InboundRule/action.json +166 -0
  89. package/entities/InboundRule/schema.json +26 -0
  90. package/entities/LSDSettings/action.json +25 -0
  91. package/entities/LSDSettings/schema.json +19 -0
  92. package/entities/Licensing/action.json +231 -0
  93. package/entities/Licensing/schema.json +29 -0
  94. package/entities/NBARApplicationManagement/action.json +106 -0
  95. package/entities/NBARApplicationManagement/schema.json +23 -0
  96. package/entities/NativeIPsec/action.json +187 -0
  97. package/entities/NativeIPsec/schema.json +27 -0
  98. package/entities/NetworkAccessAuthenticationRules/action.json +126 -0
  99. package/entities/NetworkAccessAuthenticationRules/schema.json +24 -0
  100. package/entities/NetworkAccessAuthorizationExceptionRules/action.json +126 -0
  101. package/entities/NetworkAccessAuthorizationExceptionRules/schema.json +24 -0
  102. package/entities/NetworkAccessAuthorizationGlobalExceptionRules/action.json +126 -0
  103. package/entities/NetworkAccessAuthorizationGlobalExceptionRules/schema.json +24 -0
  104. package/entities/NetworkAccessAuthorizationProfiles/action.json +25 -0
  105. package/entities/NetworkAccessAuthorizationProfiles/schema.json +19 -0
  106. package/entities/NetworkAccessAuthorizationRules/action.json +126 -0
  107. package/entities/NetworkAccessAuthorizationRules/schema.json +24 -0
  108. package/entities/NetworkAccessConditions/action.json +230 -0
  109. package/entities/NetworkAccessConditions/schema.json +29 -0
  110. package/entities/NetworkAccessDictionaries/action.json +106 -0
  111. package/entities/NetworkAccessDictionaries/schema.json +23 -0
  112. package/entities/NetworkAccessDictionaryAttributes/action.json +106 -0
  113. package/entities/NetworkAccessDictionaryAttributes/schema.json +23 -0
  114. package/entities/NetworkAccessDictionaryAttributesList/action.json +67 -0
  115. package/entities/NetworkAccessDictionaryAttributesList/schema.json +21 -0
  116. package/entities/NetworkAccessIdentityStores/action.json +25 -0
  117. package/entities/NetworkAccessIdentityStores/schema.json +19 -0
  118. package/entities/NetworkAccessMFARules/action.json +126 -0
  119. package/entities/NetworkAccessMFARules/schema.json +24 -0
  120. package/entities/NetworkAccessNetworkConditions/action.json +106 -0
  121. package/entities/NetworkAccessNetworkConditions/schema.json +23 -0
  122. package/entities/NetworkAccessPolicySets/action.json +126 -0
  123. package/entities/NetworkAccessPolicySets/schema.json +24 -0
  124. package/entities/NetworkAccessSecurityGroups/action.json +25 -0
  125. package/entities/NetworkAccessSecurityGroups/schema.json +19 -0
  126. package/entities/NetworkAccessServiceNames/action.json +25 -0
  127. package/entities/NetworkAccessServiceNames/schema.json +19 -0
  128. package/entities/NetworkAccessTimeDateConditions/action.json +106 -0
  129. package/entities/NetworkAccessTimeDateConditions/schema.json +23 -0
  130. package/entities/NodeDeployment/action.json +186 -0
  131. package/entities/NodeDeployment/schema.json +27 -0
  132. package/entities/NodeGroup/action.json +167 -0
  133. package/entities/NodeGroup/schema.json +26 -0
  134. package/entities/NodeServices/action.json +107 -0
  135. package/entities/NodeServices/schema.json +23 -0
  136. package/entities/OutboundRule/action.json +146 -0
  137. package/entities/OutboundRule/schema.json +25 -0
  138. package/entities/PANHA/action.json +45 -0
  139. package/entities/PANHA/schema.json +20 -0
  140. package/entities/Patch/action.json +252 -0
  141. package/entities/Patch/schema.json +30 -0
  142. package/entities/PatchAndHotPatch/action.json +126 -0
  143. package/entities/PatchAndHotPatch/schema.json +24 -0
  144. package/entities/PrometheusAlertmanager/action.json +330 -0
  145. package/entities/PrometheusAlertmanager/schema.json +34 -0
  146. package/entities/Proxy/action.json +45 -0
  147. package/entities/Proxy/schema.json +20 -0
  148. package/entities/PxGridCloud/action.json +107 -0
  149. package/entities/PxGridCloud/schema.json +23 -0
  150. package/entities/PxGridDirect/action.json +290 -0
  151. package/entities/PxGridDirect/schema.json +32 -0
  152. package/entities/Repository/action.json +127 -0
  153. package/entities/Repository/schema.json +24 -0
  154. package/entities/RuleFlow/action.json +24 -0
  155. package/entities/RuleFlow/schema.json +19 -0
  156. package/entities/RuleSummary/action.json +24 -0
  157. package/entities/RuleSummary/schema.json +19 -0
  158. package/entities/SXP/action.json +67 -0
  159. package/entities/SXP/schema.json +21 -0
  160. package/entities/SXPDomainsWithMappingAndDevicesCounts/action.json +25 -0
  161. package/entities/SXPDomainsWithMappingAndDevicesCounts/schema.json +19 -0
  162. package/entities/SecurityGroupManagement/action.json +25 -0
  163. package/entities/SecurityGroupManagement/schema.json +19 -0
  164. package/entities/Sgt/action.json +25 -0
  165. package/entities/Sgt/schema.json +19 -0
  166. package/entities/SgtReservation/action.json +106 -0
  167. package/entities/SgtReservation/schema.json +23 -0
  168. package/entities/SharedMappings/action.json +25 -0
  169. package/entities/SharedMappings/schema.json +19 -0
  170. package/entities/Subscriber/action.json +147 -0
  171. package/entities/Subscriber/schema.json +25 -0
  172. package/entities/TaskService/action.json +46 -0
  173. package/entities/TaskService/schema.json +20 -0
  174. package/entities/Telemetry/action.json +45 -0
  175. package/entities/Telemetry/schema.json +20 -0
  176. package/entities/TrustSecMatrixPolicy/action.json +46 -0
  177. package/entities/TrustSecMatrixPolicy/schema.json +20 -0
  178. package/entities/TrustsecIntegrationRuleDefaultTrustsecIntegrationRuleSet/action.json +25 -0
  179. package/entities/TrustsecIntegrationRuleDefaultTrustsecIntegrationRuleSet/schema.json +19 -0
  180. package/entities/TrustsecIntegrationRuleDictionaries/action.json +67 -0
  181. package/entities/TrustsecIntegrationRuleDictionaries/schema.json +21 -0
  182. package/entities/TrustsecIntegrationRuleDictionaryAttributes/action.json +130 -0
  183. package/entities/TrustsecIntegrationRuleDictionaryAttributes/schema.json +24 -0
  184. package/entities/Upgrade/action.json +168 -0
  185. package/entities/Upgrade/schema.json +26 -0
  186. package/entities/UserEquipment/action.json +188 -0
  187. package/entities/UserEquipment/schema.json +27 -0
  188. package/entities/VirtualNetworkManagement/action.json +166 -0
  189. package/entities/VirtualNetworkManagement/schema.json +26 -0
  190. package/entities/WorkloadConnection/action.json +717 -0
  191. package/entities/WorkloadConnection/schema.json +53 -0
  192. package/error.json +190 -0
  193. package/metadata.json +85 -0
  194. package/package.json +81 -0
  195. package/pronghorn.json +22101 -0
  196. package/propertiesDecorators.json +14 -0
  197. package/propertiesSchema.json +1582 -0
  198. package/report/adapterInfo.json +10 -0
  199. package/report/auto-adapter-openapi.json +18045 -0
  200. package/report/creationReport.json +3745 -0
  201. package/report/ise.json +40324 -0
  202. package/sampleProperties.json +257 -0
  203. package/test/integration/adapterTestBasicGet.js +83 -0
  204. package/test/integration/adapterTestConnectivity.js +118 -0
  205. package/test/integration/adapterTestIntegration.js +12350 -0
  206. package/test/unit/adapterBaseTestUnit.js +1024 -0
  207. package/test/unit/adapterTestUnit.js +11628 -0
  208. package/utils/adapterInfo.js +206 -0
  209. package/utils/addAuth.js +94 -0
  210. package/utils/artifactize.js +146 -0
  211. package/utils/basicGet.js +50 -0
  212. package/utils/checkMigrate.js +63 -0
  213. package/utils/entitiesToDB.js +179 -0
  214. package/utils/findPath.js +74 -0
  215. package/utils/methodDocumentor.js +273 -0
  216. package/utils/modify.js +152 -0
  217. package/utils/packModificationScript.js +35 -0
  218. package/utils/patches2bundledDeps.js +90 -0
  219. package/utils/pre-commit.sh +32 -0
  220. package/utils/removeHooks.js +20 -0
  221. package/utils/setup.js +33 -0
  222. package/utils/taskMover.js +309 -0
  223. package/utils/tbScript.js +239 -0
  224. package/utils/tbUtils.js +489 -0
  225. package/utils/testRunner.js +298 -0
  226. package/utils/troubleshootingAdapter.js +193 -0
@@ -0,0 +1,179 @@
1
+ /* @copyright Itential, LLC 2021 */
2
+
3
+ // Set globals
4
+ /* global log */
5
+
6
+ /* eslint import/no-dynamic-require: warn */
7
+ /* eslint global-require: warn */
8
+ /* eslint no-unused-vars: warn */
9
+ /* eslint import/no-unresolved: warn */
10
+ /* eslint no-promise-executor-return: warn */
11
+
12
+ /**
13
+ * This script is used to read through an adapter's entities files
14
+ * and then creates documents and enters them into the IAP mongodb
15
+ */
16
+
17
+ const fs = require('fs');
18
+ const path = require('path');
19
+ const utils = require('./tbUtils');
20
+
21
+ // get the pronghorn database information
22
+ const getPronghornProps = async (iapDir) => {
23
+ log.trace('Retrieving properties.json file...');
24
+ const rawProps = require(path.join(iapDir, 'properties.json'));
25
+ log.trace('Decrypting properties...');
26
+ const { PropertyEncryption } = require('@itential/itential-utils');
27
+ const propertyEncryption = new PropertyEncryption();
28
+ const pronghornProps = await propertyEncryption.decryptProps(rawProps);
29
+ log.trace('Found properties.\n');
30
+ return pronghornProps;
31
+ };
32
+
33
+ /**
34
+ * Function used to take a file path to a entity directory and build
35
+ * a document that corresponds to the entity files.
36
+ */
37
+ const buildDoc = (pathstring) => {
38
+ let files = fs.readdirSync(pathstring);
39
+
40
+ // load the mockdatafiles
41
+ const mockdatafiles = {};
42
+ if (files.includes('mockdatafiles') && fs.lstatSync(`${pathstring}/mockdatafiles`).isDirectory()) {
43
+ fs.readdirSync(`${pathstring}/mockdatafiles`).forEach((file) => {
44
+ if (file.split('.').pop() === 'json') {
45
+ const mockpath = `${pathstring}/mockdatafiles/${file}`;
46
+ const data = JSON.parse(fs.readFileSync(mockpath));
47
+ mockdatafiles[mockpath.split('/').pop()] = data;
48
+ }
49
+ });
50
+ }
51
+
52
+ // load the action data
53
+ let actions;
54
+ if (files.includes('action.json')) {
55
+ actions = JSON.parse(fs.readFileSync(`${pathstring}/action.json`));
56
+ }
57
+
58
+ // Load schema.json and other schemas in remaining json files
59
+ files = files.filter((f) => (f !== 'action.json') && f.endsWith('.json'));
60
+ const schema = [];
61
+ files.forEach((file) => {
62
+ const data = JSON.parse(fs.readFileSync(`${pathstring}/${file}`));
63
+ schema.push({
64
+ name: file,
65
+ schema: data
66
+ });
67
+ });
68
+
69
+ // return the data
70
+ return {
71
+ actions: actions.actions,
72
+ schema,
73
+ mockdatafiles
74
+ };
75
+ };
76
+
77
+ /**
78
+ * Function used to get the database from the options or a provided directory
79
+ */
80
+ const optionsHandler = (options) => {
81
+ // if the database properties were provided in the options - return them
82
+ if (options.pronghornProps) {
83
+ if (typeof options.pronghornProps === 'string') {
84
+ return JSON.parse(options.pronghornProps);
85
+ }
86
+ return new Promise((resolve, reject) => resolve(options.pronghornProps));
87
+ }
88
+
89
+ // if the directory was provided, get the pronghorn props from the directory
90
+ if (options.iapDir) {
91
+ return getPronghornProps(options.iapDir);
92
+ }
93
+
94
+ // if nothing was provided, error
95
+ return new Promise((resolve, reject) => reject(new Error('Neither pronghornProps nor iapDir defined in options!')));
96
+ };
97
+
98
+ /**
99
+ * Function used to put the adapter configuration into the provided database
100
+ */
101
+ const moveEntitiesToDB = async (targetPath, options) => {
102
+ // set local variables
103
+ let myOpts = options;
104
+ let myPath = targetPath;
105
+
106
+ // if we got a string parse into a JSON object
107
+ if (typeof myOpts === 'string') {
108
+ myOpts = JSON.parse(myOpts);
109
+ }
110
+
111
+ // if there is no target collection - set the collection to the default
112
+ if (!myOpts.targetCollection) {
113
+ myOpts.targetCollection = 'adapter_configs';
114
+ }
115
+
116
+ // if there is no id error since we need an id for the entities
117
+ if (!myOpts.id) {
118
+ throw new Error('Adapter ID required!');
119
+ }
120
+
121
+ // get the pronghorn database properties
122
+ return optionsHandler(options).then(async (currentProps) => {
123
+ // Check valid filepath provided
124
+ if (!myPath) {
125
+ // if no path use the current directory without the utils
126
+ myPath = path.join(__dirname, '../');
127
+ } else if (myPath.slice(-1) === '/') {
128
+ myPath = myPath.slice(0, -1);
129
+ }
130
+
131
+ // verify set the entity path
132
+ const entitiesPath = `${myPath}/entities`;
133
+ if (!fs.existsSync(entitiesPath)) {
134
+ throw new Error(`Entities path does not exist in filesystem: ${entitiesPath}`);
135
+ } else {
136
+ log.trace('Target found on filesystem');
137
+ }
138
+
139
+ // Get adapter details
140
+ if (!fs.existsSync(`${myPath}/pronghorn.json`)) {
141
+ throw new Error(`pronghorn.json does not exist in path: ${myPath}`);
142
+ } else {
143
+ log.trace('pronghorn.json found on filesystem');
144
+ }
145
+ const adapterData = JSON.parse(fs.readFileSync(`${myPath}/pronghorn.json`));
146
+
147
+ // Load files from the filesystem
148
+ const docs = [];
149
+ const entities = fs.readdirSync(entitiesPath);
150
+ entities.forEach((entity) => {
151
+ const entityPath = `${entitiesPath}/${entity}`;
152
+ const isDir = fs.lstatSync(entitiesPath).isDirectory();
153
+
154
+ // Build doc for entity
155
+ if (isDir) {
156
+ let doc = buildDoc(entityPath);
157
+ doc = {
158
+ id: myOpts.id,
159
+ type: adapterData.id,
160
+ entity,
161
+ ...doc
162
+ };
163
+ docs.push(doc);
164
+ }
165
+ });
166
+
167
+ // Upload documents to db collection
168
+ const db = await utils.connect(currentProps).catch((err) => { console.error(err); throw err; });
169
+ if (!db) {
170
+ console.error('Error occured when connectiong to database', currentProps);
171
+ throw new Error('Database not found');
172
+ }
173
+ const collection = db.collection(myOpts.targetCollection);
174
+ const res = await collection.insertMany(docs, { checkKeys: false }).catch((err) => { console.error(err); throw err; });
175
+ return res;
176
+ });
177
+ };
178
+
179
+ module.exports = { moveEntitiesToDB };
@@ -0,0 +1,74 @@
1
+ #!/usr/bin/env node
2
+ /* @copyright Itential, LLC 2019 */
3
+ /* eslint global-require:warn */
4
+ /* eslint import/no-dynamic-require:warn */
5
+ /* eslint prefer-destructuring:warn */
6
+
7
+ const path = require('path');
8
+ const fs = require('fs-extra');
9
+ const rls = require('readline-sync');
10
+
11
+ /**
12
+ * This script will determine the type of integration test to run
13
+ * based on input. If other information is needed, it will solicit
14
+ * that input and then edit the integration test accordingly.
15
+ */
16
+
17
+ /**
18
+ * Updates the action files
19
+ */
20
+ function checkActionFiles(apath) {
21
+ // verify the path
22
+ if (!apath) {
23
+ console.log(' NO PATH PROVIDED!');
24
+ return 'Done';
25
+ }
26
+
27
+ // make sure the entities directory exists
28
+ const entitydir = path.join(__dirname, '../entities');
29
+ if (!fs.statSync(entitydir).isDirectory()) {
30
+ console.log('Could not find the entities directory');
31
+ return 'error';
32
+ }
33
+
34
+ const entities = fs.readdirSync(entitydir);
35
+ let found = false;
36
+
37
+ // need to go through each entity in the entities directory
38
+ for (let e = 0; e < entities.length; e += 1) {
39
+ // make sure the entity is a directory - do not care about extra files
40
+ // only entities (dir)
41
+ if (fs.statSync(`${entitydir}/${entities[e]}`).isDirectory()) {
42
+ // see if the action file exists in the entity
43
+ if (fs.existsSync(`${entitydir}/${entities[e]}/action.json`)) {
44
+ // Read the entity actions from the file system
45
+ const actions = require(`${entitydir}/${entities[e]}/action.json`);
46
+
47
+ // go through all of the actions set the appropriate info in the newActions
48
+ for (let a = 0; a < actions.actions.length; a += 1) {
49
+ if (actions.actions[a].entitypath.indexOf(apath) >= 0) {
50
+ found = true;
51
+ console.log(` Found - entity: ${entities[e]} action: ${actions.actions[a].name}`);
52
+ console.log(` method: ${actions.actions[a].method} path: ${actions.actions[a].entitypath}`);
53
+ console.log(' ');
54
+ }
55
+ }
56
+ } else {
57
+ console.log(`Could not find entities ${entities[e]} action.json file`);
58
+ return 'error';
59
+ }
60
+ } else {
61
+ console.log(`Could not find entities ${entities[e]} directory`);
62
+ return 'error';
63
+ }
64
+ }
65
+
66
+ if (!found) {
67
+ console.log(' PATH NOT FOUND!');
68
+ }
69
+ return 'Done';
70
+ }
71
+
72
+ const findPath = rls.question('Enter the path/partial path you are looking for: ');
73
+ console.log(`PATH: ${findPath}`);
74
+ checkActionFiles(findPath);
@@ -0,0 +1,273 @@
1
+ /* eslint global-require:warn */
2
+ /* eslint import/no-dynamic-require:warn */
3
+ /* eslint no-param-reassign:warn */
4
+
5
+ const fs = require('fs-extra');
6
+ const acorn = require('acorn');
7
+
8
+ // Getting the base directory:
9
+ let adaptdir = __dirname;
10
+ if (adaptdir.endsWith('/utils')) {
11
+ adaptdir = adaptdir.substring(0, adaptdir.length - 6);
12
+ }
13
+
14
+ function createObjectForFunction(
15
+ funcName,
16
+ funcArgs,
17
+ entityPath,
18
+ description,
19
+ workflow
20
+ ) {
21
+ const funcObject = {};
22
+ // if the entity path is not set, then the object is not created.
23
+ if (entityPath !== undefined) {
24
+ funcObject.method_signature = `${funcName}(${funcArgs.join(', ')})`;
25
+ funcObject.path = entityPath;
26
+ if (description === undefined) {
27
+ funcObject.description = '';
28
+ funcObject.workflow = 'No';
29
+ } else {
30
+ funcObject.description = description;
31
+ funcObject.workflow = workflow;
32
+ }
33
+ }
34
+ return funcObject;
35
+ }
36
+
37
+ function getPathFromEntity(entity, funcName) {
38
+ let epath;
39
+ if (entity === undefined || entity === '.generic') {
40
+ epath = undefined;
41
+ } else {
42
+ // Access the action.js file for the certain entity to get the path
43
+ const entityPath = `${adaptdir}/entities/${entity}/action.json`;
44
+ const actionJSON = require(entityPath);
45
+ actionJSON.actions.forEach((action) => {
46
+ if (action.name === funcName) {
47
+ if (typeof action.entitypath === 'object') {
48
+ epath = '';
49
+ const keys = Object.keys(action.entitypath);
50
+ for (let k = 0; k < keys.length; k += 1) {
51
+ epath += `${keys[k]}:${action.entitypath[keys[k]]} <br /> `;
52
+ }
53
+ epath = epath.substring(0, epath.length - 8);
54
+ } else {
55
+ epath = action.entitypath;
56
+ }
57
+ }
58
+ });
59
+ }
60
+ return epath;
61
+ }
62
+
63
+ function recurseCallExpressions(statement, callList) {
64
+ // Recursively finds all CallExpressions in the syntax tree
65
+ if (statement.type === 'CallExpression') callList.push(statement);
66
+ const keys = Object.keys(statement);
67
+ for (let k = 0; k < keys.length; k += 1) {
68
+ if (typeof statement[keys[k]] === 'object' && statement[keys[k]] !== null) {
69
+ recurseCallExpressions(statement[keys[k]], callList);
70
+ }
71
+ }
72
+ }
73
+
74
+ function readFileUsingLib(filename, descriptionObj, workflowObj, functionList) {
75
+ // read the file
76
+ const aFile = fs.readFileSync(filename, 'utf8');
77
+ // parsing the file to get the function and class declarations.
78
+ const aFileFuncArgs = acorn.parse(aFile, { ecmaVersion: 2020 });
79
+
80
+ let callName = 'identifyRequest';
81
+ // Looping through all the declarations parsed:
82
+ aFileFuncArgs.body.forEach((e) => {
83
+ // Getting only the class declaration as it has our required functions.
84
+ if (e.type === 'ClassDeclaration') {
85
+ const methodDefinition = e.body;
86
+ methodDefinition.body.forEach((method) => {
87
+ // Getting method name and its params in the class.
88
+ const funcName = method.key.name;
89
+ const funcArgs = [];
90
+ method.value.params.forEach((param) => {
91
+ if (param.type === 'Identifier') {
92
+ funcArgs.push(param.name);
93
+ } else if (param.type === 'RestElement') {
94
+ funcArgs.push(`...${param.argument.name}`);
95
+ } else {
96
+ const args = `${param.left.name} = ${param.right.raw}`;
97
+ funcArgs.push(args);
98
+ }
99
+ });
100
+
101
+ // Getting the entity for the method:
102
+ const callList = [];
103
+ method.value.body.body.forEach((statement) => {
104
+ recurseCallExpressions(statement, callList);
105
+ });
106
+ const requests = [];
107
+ for (let i = 0; i < callList.length; i += 1) {
108
+ if (callList[i].callee.property && callList[i].callee.property.name === callName) {
109
+ requests.push(callList[i]);
110
+ }
111
+ }
112
+ if (requests.length > 0) {
113
+ const expr = requests[0];
114
+ if (expr.arguments.length < 2) {
115
+ throw new Error(`Bad inputs in method ${funcName}`);
116
+ }
117
+ const entity = expr.arguments[0].value;
118
+ const actionName = expr.arguments[1].value;
119
+ if (expr !== undefined && (expr.arguments[0].type !== 'Literal' || expr.arguments[1].type !== 'Literal')) {
120
+ const param1 = method.value.params[0];
121
+ const param2 = method.value.params[1];
122
+ if (param1.type !== 'Identifier' || param2.type !== 'Identifier'
123
+ || expr.arguments[0].type !== 'Identifier' || expr.arguments[1].type !== 'Identifier'
124
+ || param1.name !== expr.arguments[0].name || param2.name !== expr.arguments[1].name) {
125
+ throw new Error(`identifyRequest proxy method ${funcName} unknown format`);
126
+ } else if (callName !== 'identifyRequest') {
127
+ throw new Error(`MethodDocumentor not yet programmed to handle multiple helper methods: 1) ${callName}, 2) ${funcName}`);
128
+ }
129
+ callName = funcName;
130
+ }
131
+ const entityPath = getPathFromEntity(entity, actionName);
132
+
133
+ // Creating and storing the object for the method.
134
+ if (entityPath !== undefined) {
135
+ functionList.push(
136
+ createObjectForFunction(
137
+ funcName,
138
+ funcArgs,
139
+ entityPath,
140
+ descriptionObj[funcName],
141
+ workflowObj[funcName]
142
+ )
143
+ );
144
+ }
145
+ }
146
+ });
147
+ }
148
+ });
149
+ }
150
+
151
+ function readJSONFile(filename, descriptionObj, workflowObj) {
152
+ // Accessing the JSON file.
153
+ const phJSON = require(filename);
154
+ // Getting the methods array.
155
+ const methodArray = phJSON.methods;
156
+ methodArray.forEach((methodName) => {
157
+ // Getting the method description and workflow:
158
+ const funcName = methodName.name;
159
+ descriptionObj[funcName] = methodName.summary ? methodName.summary : methodName.description;
160
+ workflowObj[funcName] = methodName.task ? 'Yes' : 'No';
161
+ });
162
+ }
163
+
164
+ function readMDFile(filename, functionList) {
165
+ // Reading in the .md file and creating an array with each line as an element.
166
+ const mdFile = fs.readFileSync(filename, 'utf-8');
167
+ const fileSplit = mdFile.split('\n');
168
+ // Storing the data that should added later to the updated data.
169
+ const linesToAddLater = [];
170
+ let index = fileSplit.length - 1;
171
+
172
+ // Removing all the blank lines at the end of the file.
173
+ if (fileSplit[index] === '') {
174
+ while (fileSplit[index] === '') {
175
+ linesToAddLater.push(fileSplit.pop());
176
+ index -= 1;
177
+ }
178
+ }
179
+
180
+ // Checking if the last 2 lines are <br> and </table>. If not, the file is corrupted and the
181
+ // data at the end of the file should be fixed.
182
+ if (fileSplit[index] === '<br>' || fileSplit[index - 1] === '</table>') {
183
+ // Storing <br> and </table> to add later.
184
+ linesToAddLater.push(fileSplit.pop());
185
+ linesToAddLater.push(fileSplit.pop());
186
+ index -= 2;
187
+ } else {
188
+ console.log('The file has bad content at the end.');
189
+ return;
190
+ }
191
+ // if (fileSplit[index] !== '<br>' && fileSplit[index - 1] !== '</table>') {
192
+ // console.log('The file has bad content at the end.');
193
+ // return;
194
+ // } else {
195
+ // // Storing <br> and </table> to add later.
196
+ // linesToAddLater.push(fileSplit.pop());
197
+ // linesToAddLater.push(fileSplit.pop());
198
+ // index -= 2;
199
+ // }
200
+
201
+ // Removing all the lines until the header tags are reached.
202
+ while (!fileSplit[index].includes('<th')) {
203
+ fileSplit.pop();
204
+ index -= 1;
205
+ }
206
+ // Adding </tr> for the header row, because it got removed in the above loop.
207
+ fileSplit.push(' </tr>');
208
+
209
+ // Creating the tags for each method to be appended to the file.
210
+ const tdBeginTag = ' <td style="padding:15px">';
211
+ const tdEndTag = '</td>';
212
+
213
+ functionList.forEach((func) => {
214
+ const signCommand = `${tdBeginTag}${func.method_signature}${tdEndTag}`;
215
+ const descCommand = `${tdBeginTag}${func.description}${tdEndTag}`;
216
+ const pathCommand = `${tdBeginTag}${func.path}${tdEndTag}`;
217
+ const workflowCommand = `${tdBeginTag}${func.workflow}${tdEndTag}`;
218
+ fileSplit.push(' <tr>');
219
+ fileSplit.push(signCommand);
220
+ fileSplit.push(descCommand);
221
+ fileSplit.push(pathCommand);
222
+ fileSplit.push(workflowCommand);
223
+ fileSplit.push(' </tr>');
224
+ });
225
+
226
+ // Adding </table> and <br> at the end of the file to complete the table and the file.
227
+ while (linesToAddLater.length > 0) {
228
+ fileSplit.push(linesToAddLater.pop());
229
+ }
230
+
231
+ // Writing all the content back into the file.
232
+ fs.writeFileSync(filename, fileSplit.join('\n'), {
233
+ encoding: 'utf-8',
234
+ flag: 'w'
235
+ });
236
+ }
237
+
238
+ function getFileInfo() {
239
+ // If files don't exist:
240
+ if (!fs.existsSync(`${adaptdir}/adapter.js`)) {
241
+ console.log('Missing - utils/adapter.js');
242
+ return;
243
+ }
244
+ if (!fs.existsSync(`${adaptdir}/pronghorn.json`)) {
245
+ console.log('Missing - pronghorn.json');
246
+ return;
247
+ }
248
+ if (!fs.existsSync(`${adaptdir}/CALLS.md`)) {
249
+ console.log('Missing - CALLS.md');
250
+ return;
251
+ }
252
+
253
+ const descriptionObj = {};
254
+ const workflowObj = {};
255
+
256
+ // Get the method descriptions and the workflow values from pronghorn.json file.
257
+ readJSONFile(`${adaptdir}/pronghorn.json`, descriptionObj, workflowObj);
258
+
259
+ // Get the method signature, entity path and create an object that contains all the info regarding
260
+ // the method and push it to the functionList array.
261
+ const functionList = [];
262
+ readFileUsingLib(
263
+ `${adaptdir}/adapter.js`,
264
+ descriptionObj,
265
+ workflowObj,
266
+ functionList
267
+ );
268
+
269
+ // createMarkDown(functionList);
270
+ readMDFile(`${adaptdir}/CALLS.md`, functionList);
271
+ }
272
+
273
+ getFileInfo();
@@ -0,0 +1,152 @@
1
+ const { execSync } = require('child_process');
2
+ const fs = require('fs-extra');
3
+ const Ajv = require('ajv');
4
+ const rls = require('readline-sync');
5
+ const { existsSync } = require('fs-extra');
6
+ const { getAdapterConfig } = require('./tbUtils');
7
+ const { name } = require('../package.json');
8
+ const propertiesSchema = require('../propertiesSchema.json');
9
+
10
+ const flags = process.argv[2];
11
+
12
+ /**
13
+ * @summary Updates database instance with new adapter properties
14
+ *
15
+ * @function updateServiceItem
16
+ */
17
+ async function updateServiceItem() {
18
+ const { database, serviceItem } = await getAdapterConfig();
19
+ const currentProps = serviceItem.properties.properties;
20
+ const ajv = new Ajv({ allErrors: true, useDefaults: true });
21
+ const validate = ajv.compile(propertiesSchema);
22
+ validate(currentProps);
23
+ console.log('Updating Properties...');
24
+ await database.collection('service_configs').updateOne({ model: name }, { $set: serviceItem });
25
+ console.log('Properties Updated');
26
+ }
27
+
28
+ /**
29
+ * @summary Creates a backup zip file of current adapter
30
+ *
31
+ * @function backup
32
+ */
33
+ function backup() {
34
+ // zip all files except node_modules and package-lock
35
+ const backupCmd = 'zip -r previousVersion.zip .';
36
+ execSync(backupCmd, { encoding: 'utf-8', maxBuffer: 1024 * 1024 * 2 });
37
+ }
38
+
39
+ /**
40
+ * @summary Archives previous modifications and removes the modification package
41
+ *
42
+ * @function archiveMod
43
+ * @param {String} modType - update(UPD) or migrate(MIG)
44
+ */
45
+ function archiveMod(modType) {
46
+ if (!existsSync('./adapter_modifications/archive')) {
47
+ execSync('mkdir ./adapter_modifications/archive');
48
+ }
49
+ const zipFile = modType === 'UPD' ? 'updatePackage.zip' : 'migrationPackage.zip';
50
+ const now = new Date();
51
+ const archiveName = `${modType}-${now.toISOString()}`;
52
+ execSync(`mkdir adapter_modifications/archive/${archiveName}`);
53
+ const archiveCmd = 'mv adapter_modifications/archive .'
54
+ + ` && mv adapter_modifications/* archive/${archiveName}`
55
+ + ' && mv archive adapter_modifications'
56
+ + ` && rm ${zipFile}`;
57
+ execSync(archiveCmd, { encoding: 'utf-8' });
58
+ }
59
+
60
+ /**
61
+ * @summary Reverts modifications using backup zip file
62
+ *
63
+ * @function revertMod
64
+ */
65
+ function revertMod() {
66
+ const files = fs.readdirSync('./');
67
+ // remove all files except previousVersion
68
+ files.forEach((file) => {
69
+ if (file !== 'previousVersion.zip') {
70
+ fs.removeSync(file);
71
+ }
72
+ });
73
+ // // unzip previousVersion, reinstall dependencies and delete zipfile
74
+ execSync('unzip -o previousVersion.zip && rm -rf node_modules && rm package-lock.json && npm install', { maxBuffer: 1024 * 1024 * 2 });
75
+ execSync('rm previousVersion.zip');
76
+ console.log('Changes have been reverted');
77
+ }
78
+
79
+ // Main Script
80
+
81
+ // Migrate
82
+ if (flags === '-m') {
83
+ if (!fs.existsSync('migrationPackage.zip')) {
84
+ console.log('Migration Package not found. Download and place migrationPackage in the adapter root directory');
85
+ process.exit();
86
+ }
87
+ // Backup current adapter
88
+ backup();
89
+ console.log('Migrating adapter and running tests...');
90
+ const migrateCmd = 'unzip -o migrationPackage.zip'
91
+ + ' && cd adapter_modifications'
92
+ + ' && node migrate';
93
+ const migrateOutput = execSync(migrateCmd, { encoding: 'utf-8' });
94
+ console.log(migrateOutput);
95
+ if (migrateOutput.indexOf('Lint exited with code 1') >= 0
96
+ || migrateOutput.indexOf('Tests exited with code 1') >= 0) {
97
+ if (rls.keyInYN('Adapter failed tests or lint after migrating. Would you like to revert the changes?')) {
98
+ console.log('Reverting changes...');
99
+ revertMod();
100
+ process.exit();
101
+ }
102
+ console.log('Adapter Migration will continue. If you want to revert the changes, run the command npm run adapter:revert');
103
+ }
104
+ console.log('Installing new dependencies..');
105
+ const updatePackageCmd = 'rm -rf node_modules && rm package-lock.json && npm install';
106
+ const updatePackageOutput = execSync(updatePackageCmd, { encoding: 'utf-8' });
107
+ console.log(updatePackageOutput);
108
+ console.log('New dependencies installed');
109
+ console.log('Updating adapter properties..');
110
+ updateServiceItem().then(() => {
111
+ console.log('Adapter Successfully Migrated. Restart adapter in IAP to apply the changes');
112
+ archiveMod('MIG');
113
+ process.exit();
114
+ });
115
+ }
116
+
117
+ // Update
118
+ if (flags === '-u') {
119
+ if (!fs.existsSync('updatePackage.zip')) {
120
+ console.log('Update Package not found. Download and place updateAdapter.zip in the adapter root directory');
121
+ process.exit();
122
+ }
123
+ // Backup current adapter
124
+ backup();
125
+ const updateCmd = 'unzip -o updatePackage.zip'
126
+ + ' && cd adapter_modifications'
127
+ + ' && node update.js updateFiles';
128
+ execSync(updateCmd, { encoding: 'utf-8' });
129
+ const updateOutput = execSync(updateCmd, { encoding: 'utf-8' });
130
+ if (updateOutput.indexOf('Lint exited with code 1') >= 0
131
+ || updateOutput.indexOf('Tests exited with code 1') >= 0) {
132
+ if (rls.keyInYN('Adapter failed tests or lint after updating. Would you like to revert the changes?')) {
133
+ console.log('Reverting changes...');
134
+ revertMod();
135
+ process.exit();
136
+ }
137
+ console.log('Adapter Update will continue. If you want to revert the changes, run the command npm run adapter:revert');
138
+ }
139
+ console.log(updateOutput);
140
+ console.log('Adapter Successfully Updated. Restart adapter in IAP to apply the changes');
141
+ archiveMod('UPD');
142
+ process.exit();
143
+ }
144
+
145
+ // Revert
146
+ if (flags === '-r') {
147
+ if (!fs.existsSync('previousVersion.zip')) {
148
+ console.log('Previous adapter version not found. There are no changes to revert');
149
+ process.exit();
150
+ }
151
+ revertMod();
152
+ }