-
Notifications
You must be signed in to change notification settings - Fork 2
Add TypeScript definition generation and --types-output CLI option
#23
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
pkaminski
wants to merge
1
commit into
master
Choose a base branch
from
codex/add-optional-typescript-definitions-generation
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+1,135
−68
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,229 @@ | ||
| 'use strict'; | ||
|
|
||
| const _ = require('lodash'); | ||
| const esprima = require('esprima'); | ||
|
|
||
| class TypeGenerator { | ||
| constructor(source) { | ||
| this.source = source; | ||
| this.functionTypes = { | ||
| string: 'string', | ||
| number: 'number', | ||
| boolean: 'boolean', | ||
| any: 'any' | ||
| }; | ||
| this.functionDefinitions = {}; | ||
| this.loadFunctionDefinitions(); | ||
| this.resolveFunctionTypes(); | ||
| } | ||
|
|
||
| loadFunctionDefinitions() { | ||
| _.forEach(this.source.functions || [], definition => { | ||
| _.forEach(definition, (body, signature) => { | ||
| const match = signature.match(/^\s*(\w+)\s*(?:\((.*?)\))?\s*$/); | ||
| if (!match) return; | ||
| const name = match[1]; | ||
| const args = _.compact(_.map((match[2] || '').split(','), _.trim)); | ||
| this.functionDefinitions[name] = {body, args}; | ||
| }); | ||
| }); | ||
| } | ||
|
|
||
| resolveFunctionTypes() { | ||
| let changed = true; | ||
| while (changed) { | ||
| changed = false; | ||
| const definitions = Object.entries(this.functionDefinitions); | ||
| for (const [name, definition] of definitions) { | ||
| if (definition.args.length) continue; | ||
| const inferredType = this.inferExpressionType(definition.body); | ||
| const shouldUpdate = | ||
| inferredType && inferredType !== 'unknown' && this.functionTypes[name] !== inferredType; | ||
| if (shouldUpdate) { | ||
| this.functionTypes[name] = inferredType; | ||
| changed = true; | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| inferExpressionType(expression) { | ||
| if (!_.isString(expression)) return 'unknown'; | ||
| const parsed = this.parseConstraint(expression); | ||
| return this.disjunctionType(parsed.expression) || | ||
| this.inferSingleExpressionType(parsed.expression) || | ||
| 'unknown'; | ||
| } | ||
|
|
||
| disjunctionType(expression) { | ||
| const parts = this.disjunctionParts(expression); | ||
| if (parts.length <= 1) return; | ||
|
|
||
| const inferredTypes = _(parts) | ||
| .map(part => this.inferSingleExpressionType(part)) | ||
| .filter(type => type && type !== 'unknown') | ||
| .flatMap(type => _.map(type.split('|'), _.trim)) | ||
| .uniq() | ||
| .value(); | ||
|
|
||
| if (!inferredTypes.length) return; | ||
| return inferredTypes.join(' | '); | ||
| } | ||
|
|
||
| inferSingleExpressionType(expression) { | ||
| return this.literalConstraintType(expression) ?? | ||
| this.resolveFunctionReferenceType(expression); | ||
| } | ||
|
|
||
| disjunctionParts(expression) { | ||
| if (!_.isString(expression) || !_.includes(expression, '||')) return [expression]; | ||
|
|
||
| let parsed; | ||
| try { | ||
| parsed = esprima.parseScript(expression, {range: true}); | ||
| } catch (error) { | ||
| void error; | ||
| return _.map(expression.split('||'), _.trim); | ||
| } | ||
|
|
||
| if (!parsed.body.length || parsed.body[0].type !== 'ExpressionStatement') return [expression]; | ||
|
|
||
| const parts = []; | ||
| const stack = [parsed.body[0].expression]; | ||
| while (stack.length) { | ||
| const node = stack.pop(); | ||
| if (node.type === 'LogicalExpression' && node.operator === '||') { | ||
| stack.push(node.right); | ||
| stack.push(node.left); | ||
| continue; | ||
| } | ||
| if (!node.range) return _.map(expression.split('||'), _.trim); | ||
| parts.push(_.trim(expression.slice(node.range[0], node.range[1]))); | ||
| } | ||
| return parts; | ||
| } | ||
|
|
||
| generate() { | ||
| const root = this.toNode(this.source.root || {}); | ||
| return [ | ||
| '// Generated by fireplan. Do not edit directly.', | ||
| '', | ||
| `export type FirebaseData = ${this.typeString(root, 0)}`, | ||
| '' | ||
| ].join('\n'); | ||
| } | ||
|
|
||
| typeString(node, indent) { | ||
| if (node.kind !== 'object') return node.type; | ||
| const wildcardEntry = _.find(node.entries, {wildcard: true}); | ||
| const keepStaticEntries = !wildcardEntry || node.moreAllowed; | ||
| const rows = ['{']; | ||
| _.forEach(node.entries, entry => { | ||
| const type = this.typeString(entry.node, indent + 2); | ||
| const required = entry.required || entry.wildcard || type === 'any'; | ||
| if (entry.wildcard || keepStaticEntries) { | ||
| const key = entry.wildcard ? `[${entry.key}: string]` : entry.key; | ||
| const emittedType = entry.wildcard && node.moreAllowed ? 'any' : type; | ||
| rows.push(`${_.repeat(' ', indent + 2)}${key}${required ? '' : '?'}: ${emittedType}`); | ||
| } | ||
| }); | ||
| if (node.moreAllowed && !wildcardEntry) { | ||
| rows.push(`${_.repeat(' ', indent + 2)}[key: string]: any`); | ||
| } | ||
| rows.push(`${_.repeat(' ', indent)}}`); | ||
| return rows.join('\n'); | ||
| } | ||
|
|
||
| toNode(yaml) { | ||
| if (_.isString(yaml)) return this.fromConstraint(yaml); | ||
| if (!_.isObject(yaml) || _.isArray(yaml)) return {kind: 'leaf', type: 'unknown'}; | ||
| const childKeys = _.filter(_.keys(yaml), key => key.charAt(0) !== '.'); | ||
| if (!childKeys.length) { | ||
| if ('.value' in yaml) return this.fromConstraint(yaml['.value']); | ||
| if (yaml['.more']) return {kind: 'leaf', type: 'any'}; | ||
| return {kind: 'leaf', type: 'unknown'}; | ||
| } | ||
| return { | ||
| kind: 'object', | ||
| moreAllowed: yaml['.more'] === true, | ||
| entries: _.map(childKeys, key => { | ||
| const value = yaml[key]; | ||
| const constraint = _.isString(value) ? value : value && value['.value']; | ||
| const wildcard = key.charAt(0) === '$'; | ||
| return { | ||
| key: wildcard ? this.wildcardName(key.slice(1)) : this.propertyName(key), | ||
| wildcard, | ||
| required: wildcard || this.isRequired(constraint), | ||
| node: this.toNode(value) | ||
| }; | ||
| }) | ||
| }; | ||
| } | ||
|
|
||
| wildcardName(key) { | ||
| key = key.replace(/\/.*/, ''); | ||
| return key.match(/^[a-zA-Z_$][a-zA-Z0-9_$]*$/) ? key : 'key'; | ||
| } | ||
|
|
||
| propertyName(key) { | ||
| key = key.replace(/\/.*/, ''); | ||
| return key.match(/^[$a-zA-Z_][a-zA-Z0-9_$]*$/) ? key : JSON.stringify(key); | ||
| } | ||
|
|
||
| parseConstraint(constraint) { | ||
| if (!_.isString(constraint)) return {keywords: {}, expression: ''}; | ||
| let rest = constraint; | ||
| const keywords = {}; | ||
| while (true) { | ||
| const match = rest.match(/^\s*(required|indexed|encrypted(?:\[.*?\])?)(?:\s+|$)/); | ||
| if (!match) break; | ||
| const keyword = _.startsWith(match[1], 'encrypted') ? 'encrypted' : match[1]; | ||
| keywords[keyword] = true; | ||
| rest = rest.slice(match[0].length); | ||
| } | ||
| return {keywords, expression: _.trim(rest)}; | ||
| } | ||
|
|
||
| isRequired(constraint) { | ||
| return this.parseConstraint(constraint).keywords.required === true; | ||
| } | ||
|
|
||
| fromConstraint(constraint) { | ||
| if (!_.isString(constraint)) return {kind: 'leaf', type: 'unknown'}; | ||
| const inferredType = this.inferExpressionType(constraint); | ||
| return {kind: 'leaf', type: inferredType || 'unknown'}; | ||
| } | ||
|
|
||
| resolveFunctionReferenceType(expression) { | ||
| if (!_.isString(expression)) return; | ||
| const bareNameMatch = expression.match(/^(\w+)\b/); | ||
| if (!bareNameMatch) return; | ||
| const name = bareNameMatch[1]; | ||
| const definition = this.functionDefinitions[name]; | ||
| if (definition && definition.args.length) return; | ||
| return this.functionTypes[name]; | ||
| } | ||
|
|
||
| literalConstraintType(expression) { | ||
| const match = expression.match(/^\s*(oneOf|is)\s*\(([\s\S]*?)\)/); | ||
| if (!match) return; | ||
| let parsed; | ||
| try { | ||
| parsed = esprima.parse(`${match[1]}(${match[2]})`).body[0].expression; | ||
| } catch (error) { | ||
| void error; | ||
| return; | ||
| } | ||
| if (!parsed || parsed.type !== 'CallExpression') return; | ||
| if (parsed.callee.name !== 'oneOf' && parsed.callee.name !== 'is') return; | ||
| if (parsed.callee.name === 'is' && parsed.arguments.length !== 1) return; | ||
| return _.map(parsed.arguments, arg => { | ||
| if (arg.type === 'Literal') return JSON.stringify(arg.value); | ||
| return 'unknown'; | ||
| }).join(' | '); | ||
| } | ||
| } | ||
|
|
||
| exports.generateTypes = function(source) { | ||
| return new TypeGenerator(source).generate(); | ||
| }; | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
any-typed properties optional unless requiredThis forces every property inferred as
anyto be required in the generated type, even when the schema does not use therequiredkeyword. In Fireplan rules, child presence is only enforced viarequired, so schemas likefoo: anyare valid whenfoois absent, but the emitted type incorrectly requiresfooand causes false type errors for consumers.Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
All
requiredcontrols is whether the emitted property has a?suffix, and AFAIK there's no point in having anany-typed property be optional.