|
| 1 | +import * as E from 'fp-ts/lib/Either'; |
| 2 | +import assert from 'node:assert/strict'; |
| 3 | +import test from 'node:test'; |
| 4 | + |
| 5 | +import { TestProject } from './testProject'; |
| 6 | +import { parsePlainInitializer, type Schema } from '../src'; |
| 7 | + |
| 8 | +async function testCase( |
| 9 | + description: string, |
| 10 | + src: string, |
| 11 | + expected: Record<string, Schema>, |
| 12 | + expectedErrors: string[] = [], |
| 13 | +) { |
| 14 | + test(description, async () => { |
| 15 | + const project = new TestProject({ '/index.ts': src }); |
| 16 | + await project.parseEntryPoint('/index.ts'); |
| 17 | + const sourceFile = project.get('/index.ts'); |
| 18 | + if (sourceFile === undefined) { |
| 19 | + throw new Error('Source file not found'); |
| 20 | + } |
| 21 | + |
| 22 | + const actual: Record<string, Schema> = {}; |
| 23 | + const errors: string[] = []; |
| 24 | + for (const symbol of sourceFile.symbols.declarations) { |
| 25 | + if (symbol.init !== undefined) { |
| 26 | + const result = parsePlainInitializer(project, sourceFile, symbol.init); |
| 27 | + if (E.isLeft(result)) { |
| 28 | + // Only keep the error message, not the stack trace |
| 29 | + const errorMessage = result.left.split('\n')[0] ?? ''; |
| 30 | + errors.push(errorMessage); |
| 31 | + } else { |
| 32 | + if (symbol.comment !== undefined) { |
| 33 | + result.right.comment = symbol.comment; |
| 34 | + } |
| 35 | + actual[symbol.name] = result.right; |
| 36 | + } |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + assert.deepEqual(errors, expectedErrors); |
| 41 | + assert.deepEqual(actual, expected); |
| 42 | + }); |
| 43 | +} |
| 44 | + |
| 45 | +const MINIMAL_NESTED_MEMBER_EXPRESSION = ` |
| 46 | +import * as t from 'io-ts'; |
| 47 | +
|
| 48 | +export const colorType = { |
| 49 | + red: 'red', |
| 50 | +} as const; |
| 51 | +
|
| 52 | +export const ColorType = t.keyof(colorType); |
| 53 | +
|
| 54 | +export const redItem = t.type({ |
| 55 | + type: t.literal(ColorType.keys.red), |
| 56 | +}); |
| 57 | +`; |
| 58 | + |
| 59 | +testCase( |
| 60 | + 'nested member expression is parsed correctly', |
| 61 | + MINIMAL_NESTED_MEMBER_EXPRESSION, |
| 62 | + { |
| 63 | + colorType: { |
| 64 | + type: 'object', |
| 65 | + properties: { |
| 66 | + red: { type: 'string', enum: ['red'] }, |
| 67 | + }, |
| 68 | + required: ['red'], |
| 69 | + }, |
| 70 | + ColorType: { |
| 71 | + type: 'union', |
| 72 | + schemas: [{ type: 'string', enum: ['red'] }], |
| 73 | + }, |
| 74 | + redItem: { |
| 75 | + type: 'object', |
| 76 | + properties: { |
| 77 | + type: { type: 'string', enum: ['red'] }, |
| 78 | + }, |
| 79 | + required: ['type'], |
| 80 | + }, |
| 81 | + }, |
| 82 | +); |
0 commit comments