File size: 2,608 Bytes
5afd2f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Generate TypeScript declarations from one schema."""
import argparse
import json
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]


def type_of(node):
    if '$ref' in node:
        return node['$ref'].split('/')[-1]
    if 'const' in node:
        return json.dumps(node['const'])
    if 'enum' in node:
        return ' | '.join(json.dumps(x) for x in node['enum'])
    if 'anyOf' in node or isinstance(node.get('type'), list):
        choices = node.get('anyOf', [{'type': t} for t in node.get('type', [])])
        return ' | '.join(type_of(n) for n in choices)
    kind = node.get('type')
    if kind == 'array':
        item = type_of(node['items'])
        length = node.get('minItems')
        if length and length == node.get('maxItems'):
            return '[' + ', '.join([item] * length) + ']'
        return '(' + item + ')[]'
    if kind == 'object':
        if 'properties' not in node:
            return 'Record<string, ' + type_of(node.get('additionalProperties', {})) + '>'
        required = node.get('required', [])
        fields = [json.dumps(k) + ('' if k in required else '?') + ': ' + type_of(v)
                  for k, v in node['properties'].items()]
        if node.get('additionalProperties') is True:
            fields.append('[key: string]: unknown')
        return '{ ' + '; '.join(fields) + ' }'
    return {'string': 'string', 'number': 'number', 'integer': 'number', 'boolean': 'boolean', 'null': 'null'}.get(kind, 'unknown')


def outputs():
    defs = json.loads((ROOT / 'server/contract.schema.json').read_text())['$defs']
    ts = ['// Generated by tools/generate_contract.py; edit contract.schema.json.', '']
    ts.extend('export type ' + name + ' = ' + type_of(node) + ';' for name, node in defs.items())
    # NP run contracts are a frontend-only supplement, maintained separately
    # from the backend's segment-view schema. Keep regeneration reproducible.
    supplement = (ROOT / 'web/np-contract.ts').read_text(encoding='utf-8')
    return {ROOT / 'web/src/contract.ts': '\n'.join(ts) + '\n\n' + supplement}


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--check', action='store_true')
    args = parser.parse_args()
    for path, source in outputs().items():
        if args.check:
            if not path.is_file() or path.read_text() != source:
                raise SystemExit('contract drift: ' + str(path))
        else:
            path.parent.mkdir(parents=True, exist_ok=True)
            path.write_text(source, encoding='utf-8')


if __name__ == '__main__':
    main()