-
-
Notifications
You must be signed in to change notification settings - Fork 751
Expand file tree
/
Copy pathdefinitions.js
More file actions
265 lines (226 loc) · 8.28 KB
/
definitions.js
File metadata and controls
265 lines (226 loc) · 8.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
import fs from 'fs'
import path from 'path'
import { getConfig, getTestRoot } from './utils.js'
import Codecept from '../codecept.js'
import container from '../container.js'
import output from '../output.js'
const actingHelpers = [...container.STANDARD_ACTING_HELPERS, 'REST']
/**
* Prepare data and generate content of definitions file
* @private
*
* @param {Object} params
* @param {boolean} params.hasCustomStepsFile
* @param {boolean} params.hasCustomHelper
* @param {Map} params.supportObject
* @param {Array<string>} params.helperNames
* @param {Array<string>} params.importPaths
* @param params.translations
*
* @returns {string}
*/
const getDefinitionsFileContent = ({ hasCustomHelper, hasCustomStepsFile, helperNames, supportObject, importPaths, translations }) => {
const getHelperListFragment = ({ hasCustomHelper, hasCustomStepsFile }) => {
if (hasCustomHelper && hasCustomStepsFile) {
return `${['ReturnType<steps_file>', 'WithTranslation<Methods>'].join(', ')}`
}
if (hasCustomStepsFile) {
return 'ReturnType<steps_file>'
}
return 'WithTranslation<Methods>'
}
const helpersListFragment = getHelperListFragment({
hasCustomHelper,
hasCustomStepsFile,
})
const importPathsFragment = importPaths.join('\n')
const supportObjectsTypeFragment = convertMapToType(supportObject)
const methodsTypeFragment = helperNames.length > 0 ? `interface Methods extends ${helperNames.join(', ')} {}` : 'interface Methods {}'
const translatedActionsFragment = JSON.stringify(translations.vocabulary.actions, null, 2)
return generateDefinitionsContent({
helpersListFragment,
importPathsFragment,
supportObjectsTypeFragment,
methodsTypeFragment,
translatedActionsFragment,
})
}
/**
* Generate content for definitions file from fragments
* @private
*
* @param {Object} fragments - parts for template
* @param {string} fragments.importPathsFragment
* @param {string} fragments.supportObjectsTypeFragment
* @param {string} fragments.methodsTypeFragment
* @param {string} fragments.helpersListFragment
* @param {string} fragments.translatedActionsFragment
*
* @returns {string}
*/
const generateDefinitionsContent = ({ importPathsFragment, supportObjectsTypeFragment, methodsTypeFragment, helpersListFragment, translatedActionsFragment }) => {
return `/// <reference types='codeceptjs' />
${importPathsFragment}
declare namespace CodeceptJS {
interface SupportObject ${supportObjectsTypeFragment}
${methodsTypeFragment}
interface I extends ${helpersListFragment} {}
namespace Translation {
interface Actions ${translatedActionsFragment}
}
}
`
}
/** @type {Array<string>} */
const helperNames = []
/** @type {Array<string>} */
const customHelpers = []
export default async function (genPath, options) {
const configFile = options.config || genPath
/** @type {string} */
const testsPath = getTestRoot(configFile)
const config = await getConfig(configFile)
if (!config) return
/** @type {Object<string, string>} */
const helperPaths = {}
/** @type {Object<string, string>} */
const supportPaths = {}
/** @type {boolean} */
let hasCustomStepsFile = false
/** @type {boolean} */
let hasCustomHelper = false
/** @type {string} */
const targetFolderPath = (options.output && getTestRoot(options.output)) || testsPath
const codecept = new Codecept(config, {})
await codecept.init(testsPath)
await container.started()
const helpers = container.helpers()
const translations = container.translation()
for (const name in helpers) {
const require = codecept.config.helpers[name].require
if (require) {
helperPaths[name] = require
helperNames.push(name)
} else {
const fullBasedPromised = codecept.config.fullPromiseBased
helperNames.push(fullBasedPromised === true ? `${name}Ts` : name)
}
if (!actingHelpers.includes(name)) {
customHelpers.push(name)
}
}
let autoLogin
if (config.plugins.autoLogin) {
autoLogin = config.plugins.autoLogin.inject
}
const supportObject = new Map()
supportObject.set('I', 'I')
supportObject.set('current', 'any')
if (translations.loaded) {
supportObject.set(translations.I, translations.I)
}
if (autoLogin) {
supportObject.set(autoLogin, 'any')
}
if (customHelpers.length > 0) {
hasCustomHelper = true
}
for (const name in codecept.config.include) {
const includePath = codecept.config.include[name]
if (name === 'I' || name === translations.I) {
hasCustomStepsFile = true
supportPaths.steps_file = includePath
continue
}
supportPaths[name] = includePath
supportObject.set(name, name)
}
let definitionsFileContent = getDefinitionsFileContent({
helperNames,
supportObject,
importPaths: getImportString(testsPath, targetFolderPath, supportPaths, helperPaths),
translations,
hasCustomStepsFile,
hasCustomHelper,
})
// add aliases for translations
if (translations.loaded) {
const namespaceTranslationAliases = []
namespaceTranslationAliases.push(`interface ${translations.vocabulary.I} extends WithTranslation<Methods> {}`)
namespaceTranslationAliases.push(' namespace Translation {')
definitionsFileContent = definitionsFileContent.replace('namespace Translation {', namespaceTranslationAliases.join('\n'))
const translationAliases = []
if (translations.vocabulary.contexts) {
Object.keys(translations.vocabulary.contexts).forEach(k => {
translationAliases.push(`declare const ${translations.vocabulary.contexts[k]}: typeof ${k};`)
})
}
definitionsFileContent += `\n${translationAliases.join('\n')}`
}
if (options.dryRun) return
fs.writeFileSync(path.join(targetFolderPath, 'steps.d.ts'), definitionsFileContent)
output.print('TypeScript Definitions provide autocompletion in Visual Studio Code and other IDEs')
output.print('Definitions were generated in steps.d.ts')
}
/**
* Returns the relative path from the to the targeted folder.
* @param {string} originalPath
* @param {string} targetFolderPath
* @param {string} testsPath
*/
function getPath(originalPath, targetFolderPath, testsPath) {
const parsedPath = path.parse(originalPath)
// Remove typescript extension if exists.
if (parsedPath.base.endsWith('.d.ts')) parsedPath.base = parsedPath.base.substring(0, parsedPath.base.length - 5)
else if (parsedPath.ext === '.ts') parsedPath.base = parsedPath.name
if (!parsedPath.dir.startsWith('.')) return path.posix.join(parsedPath.dir, parsedPath.base)
const relativePath = path.posix.relative(
targetFolderPath.split(path.sep).join(path.posix.sep),
path.posix.join(testsPath.split(path.sep).join(path.posix.sep), parsedPath.dir.split(path.sep).join(path.posix.sep), parsedPath.base.split(path.sep).join(path.posix.sep)),
)
return relativePath.startsWith('.') ? relativePath : `./${relativePath}`
}
/**
*
*
* @param {string} testsPath
* @param {string} targetFolderPath
* @param {Object<string, string>} pathsToType
* @param {Object<string, string>} pathsToValue
*
* @returns {Array<string>}
*/
function getImportString(testsPath, targetFolderPath, pathsToType, pathsToValue) {
const importStrings = []
for (const name in pathsToType) {
const originalPath = pathsToType[name]
const relativePath = getPath(originalPath, targetFolderPath, testsPath)
// For .js files with plain object exports, access .default to allow TypeScript to extract properties
// For .ts files, the default export is handled differently by TypeScript
if (originalPath.endsWith('.js')) {
importStrings.push(`type ${name} = typeof import('${relativePath}').default;`)
} else {
importStrings.push(`type ${name} = typeof import('${relativePath}');`)
}
}
for (const name in pathsToValue) {
const originalPath = pathsToValue[name]
const relativePath = getPath(originalPath, targetFolderPath, testsPath)
if (originalPath.endsWith('.js') || originalPath.endsWith('.ts')) {
importStrings.push(`type ${name} = InstanceType<typeof import('${relativePath}').default>;`)
} else {
importStrings.push(`type ${name} = import('${relativePath}');`)
}
}
return importStrings
}
/**
* @param {Map} map
*
* @returns {string}
*/
function convertMapToType(map) {
return `{ ${Array.from(map)
.map(([key, value]) => `${key}: ${value}`)
.join(', ')} }`
}