-
Notifications
You must be signed in to change notification settings - Fork 182
/
buildDocs.js
213 lines (185 loc) · 5.5 KB
/
buildDocs.js
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
'use strict';
const util = require('util');
const _ = require('lodash');
const toc = require('markdown-toc');
const packageJson = require('../../package.json');
const links = require('./links');
const NO_DESCRIPTION = '_No description given._';
const COMBOS = ['anyOf', 'allOf', 'oneOf'];
const { SKIP_KEY } = require('../constants');
const walkSchemas = (InitSchema, callback) => {
const recurse = (Schema, parents) => {
parents = parents || [];
callback(Schema, parents);
Schema.dependencies.forEach((childSchema) => {
const newParents = parents.concat([InitSchema]);
recurse(childSchema, newParents);
});
};
recurse(InitSchema);
};
const collectSchemas = (InitSchema) => {
const schemas = {};
walkSchemas(InitSchema, (Schema) => {
schemas[Schema.id] = Schema;
});
return schemas;
};
const BREAK_LENGTH = 96;
const prepQuote = (val) => val.replace('`', '');
const quote = (val, triple, indent = '') =>
// either ``` with optional indentation or `
triple && val.length > BREAK_LENGTH
? '```\n' +
val
.match(/[^\r\n]+/g)
.map((line) => indent + line)
.join('\n') +
'\n' +
indent +
'```'
: `\`${prepQuote(val)}\``;
const quoteOrNa = (val, triple = false, indent = '') =>
val ? quote(val, triple, indent) : '_n/a_';
const formatExample = (example) => {
const ex = _.isPlainObject(example) ? _.omit(example, SKIP_KEY) : example;
return `* ${quoteOrNa(
util.inspect(ex, { depth: null, breakLength: BREAK_LENGTH }),
true,
' '
)}`.replace(/\s+\n/gm, '\n');
};
// Generate a display of the type (or link to a $ref).
const typeOrLink = (schema) => {
if (schema.type === 'array' && schema.items) {
return `${quoteOrNa(schema.type)}[${typeOrLink(schema.items)}]`;
}
if (schema.$ref) {
return `[${schema.$ref}](${links.anchor(schema.$ref)})`;
}
for (let i = 0; i < COMBOS.length; i++) {
const key = COMBOS[i];
if (schema[key] && schema[key].length) {
return `${key}(${schema[key].map(typeOrLink).join(', ')})`;
}
}
if (schema.enum && schema.enum.length) {
return `${quoteOrNa(schema.type)} in (${schema.enum
.map(util.inspect)
.map(quoteOrNa)
.join(', ')})`;
}
return quoteOrNa(schema.type);
};
// Properly quote and display examples.
const makeExampleSection = (Schema) => {
const examples = Schema.schema.examples || [];
if (!examples.length) {
return '';
}
return `\
#### Examples
${examples.map(formatExample).join('\n')}
`;
};
// Properly quote and display anti-examples.
const makeAntiExampleSection = (Schema) => {
const antiExamples = Schema.schema.antiExamples || [];
if (!antiExamples.length) {
return '';
}
return `\
#### Anti-Examples
${antiExamples
.map(({ example, reason }) => {
const formattedAntiExample = formatExample(example);
// If block quote, newline and indent the reason.
// Otherwise, show the reason inline w/ the anti-example and separated by a dash.
return formattedAntiExample.endsWith('```')
? `${formattedAntiExample}\n _${reason}_`
: `${formattedAntiExample} - _${reason}_`;
})
.join('\n')}
`;
};
const processProperty = (key, property, propIsRequired) => {
let isRequired = propIsRequired ? '**yes**' : 'no';
if (_.get(property, 'docAnnotation.hide')) {
return '';
} else if (_.get(property, 'docAnnotation.required')) {
// can also support keys besides "required"
const annotation = property.docAnnotation.required;
if (annotation.type === 'replace') {
isRequired = annotation.value;
} else if (annotation.type === 'append') {
isRequired += annotation.value;
} else {
throw new Error(`unrecognized docAnnotation type: ${annotation.type}`);
}
}
return `${quoteOrNa(key)} | ${isRequired} | ${typeOrLink(property)} | ${
property.description || NO_DESCRIPTION
}`;
};
// Enumerate the properties as a table.
const makePropertiesSection = (Schema) => {
const properties =
Schema.schema.properties || Schema.schema.patternProperties || {};
if (!Object.keys(properties).length) {
return '';
}
const required = Schema.schema.required || [];
return `\
#### Properties
Key | Required | Type | Description
--- | -------- | ---- | -----------
${Object.keys(properties)
.map((key) => {
const property = properties[key];
return processProperty(key, property, required.includes(key));
})
.join('\n')}
`;
};
// Given a "root" schema, create some markdown.
const makeMarkdownSection = (Schema) => {
return `\
## ${Schema.id}
${Schema.schema.description || NO_DESCRIPTION}
#### Details
* **Type** - ${typeOrLink(Schema.schema)}${
Schema.schema.pattern
? `
* **Pattern** - ${quoteOrNa(Schema.schema.pattern)}`
: ''
}
* [**Source Code**](${links.makeCodeLink(Schema.id)})
${makePropertiesSection(Schema)}
${makeExampleSection(Schema)}
${makeAntiExampleSection(Schema)}
`.trim();
};
// Generate the final markdown.
const buildDocs = (InitSchema) => {
const schemas = collectSchemas(InitSchema);
const markdownSections = _.chain(schemas)
.values()
.sortBy('id')
.map(makeMarkdownSection)
.join('\n\n-----\n\n');
const docs = `\
<!-- {% raw %} -->
# \`zapier-platform-schema\` Generated Documentation
This is automatically generated by the \`npm run docs\` command in \`zapier-platform-schema\` version ${quoteOrNa(
packageJson.version
)}.
-----
## Index
<!-- toc -->
-----
${markdownSections}
<!-- {% endraw %} -->
`.trim();
return toc.insert(docs, { maxdepth: 2, bullets: '*' });
};
module.exports = buildDocs;