1 | export namespace Code {
|
2 | export const propertyAccess = (object: string, name: string) => `${object}.${name}`
|
3 | export const quote = (str: string) => `"${str}"`
|
4 | export const nullable = (type: string) => `${type} | null`
|
5 | export const union = (name: string, types: string[]) => `type ${name} =\n| ${Code.unionItems(types)}`
|
6 | export const unionItems = (types: string[]) => types.join(`\n| `)
|
7 | export const tuple = (types: string[]) => `[${types.join(`, `)}]`
|
8 | export const list = (type: string) => `Array<${type}>`
|
9 | export const field = (name: string, type: string, options?: { optional?: boolean }) => {
|
10 | if (options?.optional) return `${name}?: ${type}`
|
11 | return `${name}: ${type}`
|
12 | }
|
13 | export const optionalField = (name: string, type: string) => Code.field(name, type, { optional: true })
|
14 | export const fields = (fieldTypes: string[]) => fieldTypes.join(`\n`)
|
15 | export const intersection = (a: string, b: string) => `${a} & ${b}`
|
16 | export const object = (fields: string) => `{\n${fields}\n}`
|
17 | export const objectFromEntries = (entries: [string, string][]) =>
|
18 | Code.objectFrom(Object.fromEntries(entries.map(([name, type]) => [name, { type }])))
|
19 | export const objectFrom = (
|
20 | object: Record<
|
21 | string,
|
22 | null | string | boolean | number | { type: null | string | boolean | number; optional?: boolean; tsdoc?: string }
|
23 | >,
|
24 | ) => {
|
25 | return Code.object(
|
26 | Code.fields(
|
27 | Object.entries(object).map(([name, spec]) =>
|
28 | [name, spec && typeof spec === `object` ? spec : { type: spec }] as const
|
29 | )
|
30 | .map((
|
31 | [name, spec],
|
32 | ) => Code.field(name, String(spec.type), { optional: spec.optional })),
|
33 | ),
|
34 | )
|
35 | }
|
36 | export const type = (name: string, type: string) => `type ${name} = ${type}`
|
37 | export const interface$ = (name: string, object: string) => `interface ${name} ${object}`
|
38 | export const export$ = (thing: string) => `export ${thing}`
|
39 | export const TSDoc = (content: string | null, block: string) =>
|
40 | content === null ? block : `\n${block}`
|
41 | export const namespace = (name: string, content: string) => `namespace ${name} ${Code.object(content)}`
|
42 | export const group = (...content: string[]) => content.join(`\n`)
|
43 | export const commentSectionTitle = (title: string) => {
|
44 | const lineSize = 60
|
45 | const line = `-`.repeat(lineSize)
|
46 | const titlePrefixSpace = ` `.repeat(Math.round(lineSize / 2) - Math.round(title.length / 2))
|
47 | const titleSuffixSpace = ` `.repeat(lineSize - (titlePrefixSpace.length + title.length))
|
48 | return `\n\n
|
49 | }
|
50 | }
|
51 |
|
52 | const prependLines = (prepend: string, str: string) => str.split(`\n`).map((line) => `${prepend}${line}`).join(`\n`)
|