-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathbuildSpecs.ts
280 lines (237 loc) · 7.14 KB
/
buildSpecs.ts
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import fsp from 'fs/promises';
import yaml from 'js-yaml';
import {
BUNDLE_WITH_DOC,
checkForCache,
exists,
run,
toAbsolutePath,
} from './common';
import { createSpinner } from './oraLog';
import type { Spec } from './types';
const ALGOLIASEARCH_LITE_OPERATIONS = ['search', 'post'];
/**
* This function will transform properties in the bundle depending on the context.
* E.g:
* - Check tags definition
* - Add name of the client in tags
* - Remove unecessary punctuation for documentation
* - etc...
*/
async function transformBundle({
bundledPath,
withDoc,
clientName,
alias,
}: {
bundledPath: string;
withDoc: boolean;
clientName: string;
alias?: string;
}): Promise<void> {
if (!(await exists(bundledPath))) {
throw new Error(`Bundled file not found ${bundledPath}.`);
}
const bundledSpec = yaml.load(
await fsp.readFile(bundledPath, 'utf8')
) as Spec;
let bundledDocSpec: Spec | undefined;
if (withDoc) {
bundledDocSpec = yaml.load(await fsp.readFile(bundledPath, 'utf8')) as Spec;
}
const tagsDefinitions = bundledSpec.tags;
for (const [pathKey, pathMethods] of Object.entries(bundledSpec.paths)) {
for (const [method, specMethod] of Object.entries(pathMethods)) {
// In the main bundle we need to have only the clientName
// because open-api-generator will use this to determine the name of the client
specMethod.tags = [clientName];
// Doc special cases
if (!withDoc || !bundledDocSpec) {
continue;
}
const docMethod = bundledDocSpec.paths[pathKey][method];
if (docMethod.summary) {
// Remove dot at the end of summary for better sidebar display
docMethod.summary = docMethod.summary.replace(/\.$/gm, '');
}
if (!docMethod.tags) {
continue;
}
// Checks that specified tags are well defined at root level
for (const tag of docMethod.tags) {
if (tag === clientName || (alias && tag === alias)) {
return;
}
const tagExists = tagsDefinitions
? tagsDefinitions.find((t) => t.name === tag)
: null;
if (!tagExists) {
throw new Error(
`Tag "${tag}" in "client[${clientName}] -> operation[${specMethod.operationId}]" is not defined`
);
}
}
}
}
await fsp.writeFile(
bundledPath,
yaml.dump(bundledSpec, {
noRefs: true,
})
);
if (withDoc) {
const docFolderPath = toAbsolutePath('website/specs');
if (!(await exists(docFolderPath))) {
fsp.mkdir(docFolderPath, { recursive: true });
}
const pathToSpecDoc = `${docFolderPath}/${clientName}.doc.yml`;
await fsp.writeFile(
pathToSpecDoc,
yaml.dump(bundledDocSpec, {
noRefs: true,
})
);
}
}
async function lintCommon(verbose: boolean, useCache: boolean): Promise<void> {
const spinner = createSpinner('linting common spec', verbose).start();
let hash = '';
const cacheFile = toAbsolutePath(`specs/dist/common.cache`);
if (useCache) {
const { cacheExists, hash: newCache } = await checkForCache({
folder: toAbsolutePath('specs/'),
generatedFiles: [],
filesToCache: ['common'],
cacheFile,
});
if (cacheExists) {
spinner.succeed("job skipped, cache found for 'common' spec");
return;
}
hash = newCache;
}
await run(`yarn specs:lint common`, { verbose });
if (hash) {
spinner.text = `storing common spec cache`;
await fsp.writeFile(cacheFile, hash);
}
spinner.succeed();
}
/**
* Creates a lite search spec with the `ALGOLIASEARCH_LITE_OPERATIONS` methods
* from the `search` spec.
*/
async function buildLiteSpec({
spec,
bundledPath,
outputFormat,
}: {
spec: string;
bundledPath: string;
outputFormat: string;
}): Promise<void> {
const parsed = yaml.load(
await fsp.readFile(toAbsolutePath(bundledPath), 'utf8')
) as Spec;
// Filter methods.
parsed.paths = Object.entries(parsed.paths).reduce(
(acc, [path, operations]) => {
for (const [method, operation] of Object.entries(operations)) {
if (
method === 'post' &&
ALGOLIASEARCH_LITE_OPERATIONS.includes(operation.operationId)
) {
return { ...acc, [path]: { post: operation } };
}
}
return acc;
},
{} as Spec['paths']
);
const liteBundledPath = `specs/bundled/${spec}.${outputFormat}`;
await fsp.writeFile(toAbsolutePath(liteBundledPath), yaml.dump(parsed));
await transformBundle({
bundledPath: toAbsolutePath(liteBundledPath),
clientName: spec,
// Lite does not need documentation because it's just a subset
withDoc: false,
});
}
/**
* Build spec file.
*/
async function buildSpec(
spec: string,
outputFormat: string,
verbose: boolean,
useCache: boolean
): Promise<void> {
const isAlgoliasearch = spec === 'algoliasearch';
// In case of lite we use a the `search` spec as a base because only its bundled form exists.
const specBase = isAlgoliasearch ? 'search' : spec;
const cacheFile = toAbsolutePath(`specs/dist/${spec}.cache`);
let hash = '';
const spinner = createSpinner(`starting '${spec}' spec`, verbose).start();
if (useCache) {
spinner.text = `checking cache for '${specBase}'`;
const { cacheExists, hash: newCache } = await checkForCache({
folder: toAbsolutePath('specs/'),
generatedFiles: [`bundled/${spec}.yml`],
filesToCache: [specBase, 'common'],
cacheFile,
});
if (cacheExists) {
spinner.succeed(`job skipped, cache found for '${specBase}'`);
return;
}
spinner.text = `cache not found for '${specBase}'`;
hash = newCache;
}
// First linting the base
spinner.text = `linting '${spec}' spec`;
await run(`yarn specs:fix ${specBase}`, { verbose });
// Then bundle the file
const bundledPath = `specs/bundled/${spec}.${outputFormat}`;
await run(
`yarn openapi bundle specs/${specBase}/spec.yml -o ${bundledPath} --ext ${outputFormat}`,
{ verbose }
);
// Add the correct tags to be able to generate the proper client
if (!isAlgoliasearch) {
await transformBundle({
bundledPath: toAbsolutePath(bundledPath),
clientName: spec,
withDoc: BUNDLE_WITH_DOC,
});
} else {
await buildLiteSpec({
spec,
bundledPath: toAbsolutePath(bundledPath),
outputFormat,
});
}
// Validate and lint the final bundle
spinner.text = `validating '${spec}' bundled spec`;
await run(`yarn openapi lint specs/bundled/${spec}.${outputFormat}`, {
verbose,
});
spinner.text = `linting '${spec}' bundled spec`;
await run(`yarn specs:fix bundled/${spec}.${outputFormat}`, { verbose });
if (hash) {
spinner.text = `storing '${spec}' spec cache`;
await fsp.writeFile(cacheFile, hash);
}
spinner.succeed(`building complete for '${spec}' spec`);
}
export async function buildSpecs(
clients: string[],
outputFormat: 'json' | 'yml',
verbose: boolean,
useCache: boolean
): Promise<void> {
await fsp.mkdir(toAbsolutePath('specs/dist'), { recursive: true });
await lintCommon(verbose, useCache);
await Promise.all(
clients.map((client) => buildSpec(client, outputFormat, verbose, useCache))
);
}