@wener/utils 1.1.47 → 1.1.49

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (194) hide show
  1. package/README.md +9 -1
  2. package/lib/asyncs/Promises.js +54 -0
  3. package/lib/asyncs/Promises.js.map +1 -0
  4. package/lib/asyncs/createLazyPromise.js +52 -51
  5. package/lib/asyncs/createLazyPromise.js.map +1 -1
  6. package/lib/asyncs/firstOfAsyncIterator.js.map +1 -1
  7. package/lib/asyncs/isPromise.js +2 -3
  8. package/lib/asyncs/isPromise.js.map +1 -1
  9. package/lib/asyncs/nextOfAsyncIterator.js.map +1 -1
  10. package/lib/asyncs/timeout.js +4 -4
  11. package/lib/asyncs/timeout.js.map +1 -1
  12. package/lib/cn/division/DivisionCode.js +30 -17
  13. package/lib/cn/division/DivisionCode.js.map +1 -1
  14. package/lib/cn/id/{Mod11Checksum.js → Mod11.js} +3 -6
  15. package/lib/cn/id/Mod11.js.map +1 -0
  16. package/lib/cn/id/ResidentIdNumber.js +10 -12
  17. package/lib/cn/id/ResidentIdNumber.js.map +1 -1
  18. package/lib/cn/types.js +3 -0
  19. package/lib/cn/types.js.map +1 -0
  20. package/lib/cn/uscc/{Mod31Checksum.js → Mod31.js} +3 -6
  21. package/lib/cn/uscc/Mod31.js.map +1 -0
  22. package/lib/cn/uscc/USCC.js +6 -9
  23. package/lib/cn/uscc/USCC.js.map +1 -1
  24. package/lib/cn/uscc/isUSCC.js +1 -1
  25. package/lib/cn/uscc/isUSCC.js.map +1 -1
  26. package/lib/crypto/getNodeCrypto.js +14 -10
  27. package/lib/crypto/getNodeCrypto.js.map +1 -1
  28. package/lib/crypto/getRandomValues.js +5 -1
  29. package/lib/crypto/getRandomValues.js.map +1 -1
  30. package/lib/emitter/types.js +3 -0
  31. package/lib/emitter/types.js.map +1 -0
  32. package/lib/fetch/createFetchWith.js.map +1 -1
  33. package/lib/fetch/createFetchWithRetry.js.map +1 -1
  34. package/lib/fetch/http.types.js +4 -0
  35. package/lib/fetch/http.types.js.map +1 -0
  36. package/lib/index.js +6 -3
  37. package/lib/index.js.map +1 -1
  38. package/lib/io/ArrayBuffers.js.map +1 -1
  39. package/lib/io/ByteBuffer.js +235 -36
  40. package/lib/io/ByteBuffer.js.map +1 -1
  41. package/lib/langs/getGlobalStates.js +17 -0
  42. package/lib/langs/getGlobalStates.js.map +1 -0
  43. package/lib/langs/getObjectId.js +18 -0
  44. package/lib/langs/getObjectId.js.map +1 -0
  45. package/lib/langs/isNullish.js +5 -0
  46. package/lib/langs/isNullish.js.map +1 -0
  47. package/lib/logging/slog.js.map +1 -1
  48. package/lib/maths/clamp.js +7 -6
  49. package/lib/maths/clamp.js.map +1 -1
  50. package/lib/maths/random.js.map +1 -1
  51. package/lib/mitt/index.js +77 -0
  52. package/lib/mitt/index.js.map +1 -0
  53. package/lib/objects/computeIfAbsent.js +1 -1
  54. package/lib/objects/computeIfAbsent.js.map +1 -1
  55. package/lib/schema/typebox/typebox.js.map +1 -1
  56. package/lib/server/fetch/createFetchWithProxyByUndici.js.map +1 -1
  57. package/package.json +6 -14
  58. package/src/asyncs/Promises.ts +62 -0
  59. package/src/asyncs/createLazyPromise.test.ts +52 -13
  60. package/src/asyncs/createLazyPromise.ts +66 -61
  61. package/src/asyncs/firstOfAsyncIterator.ts +1 -1
  62. package/src/asyncs/isPromise.ts +3 -3
  63. package/src/asyncs/nextOfAsyncIterator.ts +1 -1
  64. package/src/asyncs/timeout.ts +4 -4
  65. package/src/cn/division/DivisionCode.ts +61 -8
  66. package/src/cn/division/division.test.ts +6 -0
  67. package/src/cn/id/{Mod11Checksum.ts → Mod11.ts} +3 -6
  68. package/src/cn/id/ResidentIdNumber.ts +11 -13
  69. package/src/cn/id/id.test.ts +5 -5
  70. package/src/cn/scripts/gen.test.ts +2 -1
  71. package/src/cn/types.ts +11 -0
  72. package/src/cn/uscc/{Mod31Checksum.ts → Mod31.ts} +3 -7
  73. package/src/cn/uscc/USCC.ts +7 -11
  74. package/src/cn/uscc/isUSCC.ts +1 -1
  75. package/src/cn/uscc/uscc.test.ts +4 -4
  76. package/src/crypto/getNodeCrypto.ts +16 -11
  77. package/src/crypto/getRandomValues.ts +6 -1
  78. package/src/emitter/types.ts +18 -0
  79. package/src/fetch/createFetchWith.ts +1 -1
  80. package/src/fetch/createFetchWithRetry.ts +1 -1
  81. package/src/fetch/http.types.ts +46 -0
  82. package/src/index.ts +7 -3
  83. package/src/io/ArrayBuffers.ts +7 -3
  84. package/src/io/ByteBuffer.test.ts +33 -6
  85. package/src/io/ByteBuffer.ts +272 -41
  86. package/src/langs/getGlobalStates.ts +21 -0
  87. package/src/langs/getObjectId.ts +20 -0
  88. package/src/langs/isNullish.ts +3 -0
  89. package/src/langs/mixin.test.ts +43 -0
  90. package/src/logging/slog.ts +1 -1
  91. package/src/maths/clamp.test.ts +5 -1
  92. package/src/maths/clamp.ts +7 -7
  93. package/src/maths/random.ts +1 -1
  94. package/src/mitt/README.md +1 -0
  95. package/src/mitt/index.ts +114 -0
  96. package/src/objects/computeIfAbsent.ts +3 -2
  97. package/src/objects/merge/merge.test.ts +1 -1
  98. package/src/schema/typebox/typebox.ts +1 -1
  99. package/src/server/fetch/createFetchWithProxyByUndici.ts +2 -2
  100. package/tsconfig.json +4 -1
  101. package/lib/asyncs/sleep.js +0 -3
  102. package/lib/asyncs/sleep.js.map +0 -1
  103. package/lib/cn/id/Mod11Checksum.js.map +0 -1
  104. package/lib/cn/uscc/Mod31Checksum.js.map +0 -1
  105. package/lib/schema/typebox/gen/codegen/common/encoder.js +0 -94
  106. package/lib/schema/typebox/gen/codegen/common/encoder.js.map +0 -1
  107. package/lib/schema/typebox/gen/codegen/common/formatter.js +0 -33
  108. package/lib/schema/typebox/gen/codegen/common/formatter.js.map +0 -1
  109. package/lib/schema/typebox/gen/codegen/common/index.js +0 -29
  110. package/lib/schema/typebox/gen/codegen/common/index.js.map +0 -1
  111. package/lib/schema/typebox/gen/codegen/common/jsdoc.js +0 -117
  112. package/lib/schema/typebox/gen/codegen/common/jsdoc.js.map +0 -1
  113. package/lib/schema/typebox/gen/codegen/expression/compiler.js +0 -364
  114. package/lib/schema/typebox/gen/codegen/expression/compiler.js.map +0 -1
  115. package/lib/schema/typebox/gen/codegen/expression/errors.js +0 -259
  116. package/lib/schema/typebox/gen/codegen/expression/errors.js.map +0 -1
  117. package/lib/schema/typebox/gen/codegen/expression/evaluator.js +0 -254
  118. package/lib/schema/typebox/gen/codegen/expression/evaluator.js.map +0 -1
  119. package/lib/schema/typebox/gen/codegen/expression/expression.js +0 -381
  120. package/lib/schema/typebox/gen/codegen/expression/expression.js.map +0 -1
  121. package/lib/schema/typebox/gen/codegen/expression/index.js +0 -32
  122. package/lib/schema/typebox/gen/codegen/expression/index.js.map +0 -1
  123. package/lib/schema/typebox/gen/codegen/index.js +0 -29
  124. package/lib/schema/typebox/gen/codegen/index.js.map +0 -1
  125. package/lib/schema/typebox/gen/codegen/model/index.js +0 -40
  126. package/lib/schema/typebox/gen/codegen/model/index.js.map +0 -1
  127. package/lib/schema/typebox/gen/codegen/model/model-to-arktype.js +0 -260
  128. package/lib/schema/typebox/gen/codegen/model/model-to-arktype.js.map +0 -1
  129. package/lib/schema/typebox/gen/codegen/model/model-to-expression.js +0 -383
  130. package/lib/schema/typebox/gen/codegen/model/model-to-expression.js.map +0 -1
  131. package/lib/schema/typebox/gen/codegen/model/model-to-grpc.js +0 -238
  132. package/lib/schema/typebox/gen/codegen/model/model-to-grpc.js.map +0 -1
  133. package/lib/schema/typebox/gen/codegen/model/model-to-io-ts.js +0 -274
  134. package/lib/schema/typebox/gen/codegen/model/model-to-io-ts.js.map +0 -1
  135. package/lib/schema/typebox/gen/codegen/model/model-to-javascript.js +0 -47
  136. package/lib/schema/typebox/gen/codegen/model/model-to-javascript.js.map +0 -1
  137. package/lib/schema/typebox/gen/codegen/model/model-to-json-schema.js +0 -192
  138. package/lib/schema/typebox/gen/codegen/model/model-to-json-schema.js.map +0 -1
  139. package/lib/schema/typebox/gen/codegen/model/model-to-typebox.js +0 -33
  140. package/lib/schema/typebox/gen/codegen/model/model-to-typebox.js.map +0 -1
  141. package/lib/schema/typebox/gen/codegen/model/model-to-typescript.js +0 -188
  142. package/lib/schema/typebox/gen/codegen/model/model-to-typescript.js.map +0 -1
  143. package/lib/schema/typebox/gen/codegen/model/model-to-valibot.js +0 -239
  144. package/lib/schema/typebox/gen/codegen/model/model-to-valibot.js.map +0 -1
  145. package/lib/schema/typebox/gen/codegen/model/model-to-value.js +0 -43
  146. package/lib/schema/typebox/gen/codegen/model/model-to-value.js.map +0 -1
  147. package/lib/schema/typebox/gen/codegen/model/model-to-yrel.js +0 -227
  148. package/lib/schema/typebox/gen/codegen/model/model-to-yrel.js.map +0 -1
  149. package/lib/schema/typebox/gen/codegen/model/model-to-yup.js +0 -225
  150. package/lib/schema/typebox/gen/codegen/model/model-to-yup.js.map +0 -1
  151. package/lib/schema/typebox/gen/codegen/model/model-to-zod.js +0 -248
  152. package/lib/schema/typebox/gen/codegen/model/model-to-zod.js.map +0 -1
  153. package/lib/schema/typebox/gen/codegen/model/model.js +0 -27
  154. package/lib/schema/typebox/gen/codegen/model/model.js.map +0 -1
  155. package/lib/schema/typebox/gen/codegen/typescript/index.js +0 -28
  156. package/lib/schema/typebox/gen/codegen/typescript/index.js.map +0 -1
  157. package/lib/schema/typebox/gen/codegen/typescript/typescript-to-model.js +0 -72
  158. package/lib/schema/typebox/gen/codegen/typescript/typescript-to-model.js.map +0 -1
  159. package/lib/schema/typebox/gen/codegen/typescript/typescript-to-typebox.js +0 -620
  160. package/lib/schema/typebox/gen/codegen/typescript/typescript-to-typebox.js.map +0 -1
  161. package/lib/schema/typebox/gen/index.js +0 -3
  162. package/lib/schema/typebox/gen/index.js.map +0 -1
  163. package/src/asyncs/sleep.ts +0 -1
  164. package/src/schema/typebox/gen/codegen/common/encoder.ts +0 -99
  165. package/src/schema/typebox/gen/codegen/common/formatter.ts +0 -31
  166. package/src/schema/typebox/gen/codegen/common/index.ts +0 -29
  167. package/src/schema/typebox/gen/codegen/common/jsdoc.ts +0 -93
  168. package/src/schema/typebox/gen/codegen/expression/compiler.ts +0 -377
  169. package/src/schema/typebox/gen/codegen/expression/errors.ts +0 -302
  170. package/src/schema/typebox/gen/codegen/expression/evaluator.ts +0 -268
  171. package/src/schema/typebox/gen/codegen/expression/expression.ts +0 -538
  172. package/src/schema/typebox/gen/codegen/expression/index.ts +0 -32
  173. package/src/schema/typebox/gen/codegen/index.ts +0 -29
  174. package/src/schema/typebox/gen/codegen/model/index.ts +0 -40
  175. package/src/schema/typebox/gen/codegen/model/model-to-arktype.ts +0 -266
  176. package/src/schema/typebox/gen/codegen/model/model-to-expression.ts +0 -378
  177. package/src/schema/typebox/gen/codegen/model/model-to-grpc.ts +0 -244
  178. package/src/schema/typebox/gen/codegen/model/model-to-io-ts.ts +0 -294
  179. package/src/schema/typebox/gen/codegen/model/model-to-javascript.ts +0 -42
  180. package/src/schema/typebox/gen/codegen/model/model-to-json-schema.ts +0 -166
  181. package/src/schema/typebox/gen/codegen/model/model-to-typebox.ts +0 -32
  182. package/src/schema/typebox/gen/codegen/model/model-to-typescript.ts +0 -189
  183. package/src/schema/typebox/gen/codegen/model/model-to-valibot.ts +0 -236
  184. package/src/schema/typebox/gen/codegen/model/model-to-value.ts +0 -42
  185. package/src/schema/typebox/gen/codegen/model/model-to-yrel.ts +0 -232
  186. package/src/schema/typebox/gen/codegen/model/model-to-yup.ts +0 -226
  187. package/src/schema/typebox/gen/codegen/model/model-to-zod.ts +0 -251
  188. package/src/schema/typebox/gen/codegen/model/model.ts +0 -33
  189. package/src/schema/typebox/gen/codegen/typescript/index.ts +0 -28
  190. package/src/schema/typebox/gen/codegen/typescript/typescript-to-model.ts +0 -61
  191. package/src/schema/typebox/gen/codegen/typescript/typescript-to-typebox.ts +0 -647
  192. package/src/schema/typebox/gen/gen.test.ts +0 -12
  193. package/src/schema/typebox/gen/index.ts +0 -1
  194. /package/src/schema/{typebox/gen/README.md → README.md} +0 -0
@@ -1,647 +0,0 @@
1
- /*--------------------------------------------------------------------------
2
-
3
- @sinclair/typebox-codegen
4
-
5
- The MIT License (MIT)
6
-
7
- Permission is hereby granted, free of charge, to any person obtaining a copy
8
- of this software and associated documentation files (the "Software"), to deal
9
- in the Software without restriction, including without limitation the rights
10
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
- copies of the Software, and to permit persons to whom the Software is
12
- furnished to do so, subject to the following conditions:
13
-
14
- The above copyright notice and this permission notice shall be included in
15
- all copies or substantial portions of the Software.
16
-
17
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23
- THE SOFTWARE.
24
-
25
- ---------------------------------------------------------------------------*/
26
- import * as ts from 'typescript';
27
- import { JsDoc } from '../common/jsdoc';
28
-
29
- export class TypeScriptToTypeBoxError extends Error {
30
- constructor(public readonly diagnostics: ts.Diagnostic[]) {
31
- super('');
32
- }
33
- }
34
- // --------------------------------------------------------------------------
35
- // TypeScriptToTypeBox
36
- // --------------------------------------------------------------------------
37
-
38
- export interface TypeScriptToTypeBoxOptions {
39
- /**
40
- * Setting this to true will ensure all types are exports as const values. This setting is
41
- * used by the TypeScriptToTypeBoxModel to gather TypeBox definitions during runtime eval
42
- * pass. The default is false
43
- */
44
- useExportEverything?: boolean;
45
- /**
46
- * Specifies if the output code should specify a default `import` statement. For TypeScript
47
- * generated code this is typically desirable, but for Model generated code, the `Type`
48
- * build is passed in into scope as a variable. The default is true.
49
- */
50
- useTypeBoxImport?: boolean;
51
- /**
52
- * Specifies if the output types should include an identifier associated with the assigned
53
- * variable name. This is useful for remapping model types to targets, but optional for
54
- * for TypeBox which can operate on vanilla JS references. The default is false.
55
- */
56
- useIdentifiers?: boolean;
57
- }
58
- /** Generates TypeBox types from TypeScript code */
59
- export namespace TypeScriptToTypeBox {
60
- // ------------------------------------------------------------------------------------------------------------
61
- // Transpile Options
62
- // ------------------------------------------------------------------------------------------------------------
63
- const transpilerOptions: ts.TranspileOptions = {
64
- compilerOptions: {
65
- strict: true,
66
- target: ts.ScriptTarget.ES2022,
67
- },
68
- };
69
- // ------------------------------------------------------------------------------------------------------------
70
- // Transpile States
71
- // ------------------------------------------------------------------------------------------------------------
72
- // (auto) tracked on calls to find type name
73
- const typenames = new Set<string>();
74
- // (auto) tracked for recursive types and used to associate This type references
75
- let recursiveDeclaration: ts.TypeAliasDeclaration | ts.InterfaceDeclaration | null = null;
76
- // (auto) tracked for scoped block level definitions and used to prevent `export` emit when not in global scope.
77
- let blockLevel: number = 0;
78
- // (auto) tracked for injecting typebox import statements
79
- let useImports = false;
80
- // (auto) tracked for injecting JSON schema optios
81
- let useOptions = false;
82
- // (auto) tracked for injecting TSchema import statements
83
- let useGenerics = false;
84
- // (auto) tracked for cases where composition requires deep clone
85
- let useCloneType = false;
86
- // (option) export override to ensure all schematics
87
- let useExportsEverything = false;
88
- // (option) inject identifiers
89
- let useIdentifiers = false;
90
- // (option) specifies if typebox imports should be included
91
- let useTypeBoxImport = true;
92
- // ------------------------------------------------------------------------------------------------------------
93
- // AST Query
94
- // ------------------------------------------------------------------------------------------------------------
95
- function FindRecursiveParent(decl: ts.InterfaceDeclaration | ts.TypeAliasDeclaration, node: ts.Node): boolean {
96
- return (
97
- (ts.isTypeReferenceNode(node) && decl.name.getText() === node.typeName.getText()) ||
98
- node.getChildren().some((node) => FindRecursiveParent(decl, node))
99
- );
100
- }
101
- function FindRecursiveThis(node: ts.Node): boolean {
102
- return node.getChildren().some((node) => ts.isThisTypeNode(node) || FindRecursiveThis(node));
103
- }
104
- function FindTypeName(node: ts.Node, name: string): boolean {
105
- const found =
106
- typenames.has(name) ||
107
- node.getChildren().some((node) => {
108
- return (
109
- ((ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node)) && node.name.getText() === name) ||
110
- FindTypeName(node, name)
111
- );
112
- });
113
- if (found) typenames.add(name);
114
- return found;
115
- }
116
- function IsRecursiveType(decl: ts.InterfaceDeclaration | ts.TypeAliasDeclaration) {
117
- const check1 = ts.isTypeAliasDeclaration(decl)
118
- ? [decl.type].some((node) => FindRecursiveParent(decl, node))
119
- : decl.members.some((node) => FindRecursiveParent(decl, node));
120
- const check2 = ts.isInterfaceDeclaration(decl) && FindRecursiveThis(decl);
121
- return check1 || check2;
122
- }
123
- function IsReadonlyProperty(node: ts.PropertySignature): boolean {
124
- return (
125
- node.modifiers !== undefined && node.modifiers.find((modifier) => modifier.getText() === 'readonly') !== undefined
126
- );
127
- }
128
- function IsOptionalProperty(node: ts.PropertySignature) {
129
- return node.questionToken !== undefined;
130
- }
131
- function IsExport(
132
- node: ts.InterfaceDeclaration | ts.TypeAliasDeclaration | ts.EnumDeclaration | ts.ModuleDeclaration,
133
- ): boolean {
134
- return (
135
- blockLevel === 0 &&
136
- (useExportsEverything ||
137
- (node.modifiers !== undefined &&
138
- node.modifiers.find((modifier) => modifier.getText() === 'export') !== undefined))
139
- );
140
- }
141
- function IsNamespace(node: ts.ModuleDeclaration) {
142
- return node.flags === ts.NodeFlags.Namespace;
143
- }
144
- // ------------------------------------------------------------------------------------------------------------
145
- // Options
146
- // ------------------------------------------------------------------------------------------------------------
147
- function ResolveJsDocComment(
148
- node: ts.TypeAliasDeclaration | ts.PropertySignature | ts.InterfaceDeclaration | ts.LiteralTypeNode,
149
- ): string {
150
- const content = node.getFullText().trim();
151
- if (node.kind === ts.SyntaxKind.LiteralType) {
152
- if (content.startsWith('/**')) {
153
- // add a new line for JsDoc to parse properly
154
- return content.slice(0, content.lastIndexOf('*/') + 2).replace(/\*+\/$/, '\n$0');
155
- } else {
156
- return '';
157
- }
158
- }
159
- const indices = [content.indexOf('/**'), content.indexOf('type'), content.indexOf('interface')].map((n) =>
160
- n === -1 ? Infinity : n,
161
- );
162
- if (indices[0] === -1 || indices[1] < indices[0] || indices[2] < indices[0]) return ''; // no comment or declaration before comment
163
- for (let i = indices[0]; i < content.length; i++) {
164
- if (content[i] === '*' && content[i + 1] === '/') return content.slice(0, i + 2);
165
- }
166
- return '';
167
- }
168
- function ResolveOptions(
169
- node: ts.TypeAliasDeclaration | ts.PropertySignature | ts.InterfaceDeclaration | ts.LiteralTypeNode,
170
- ): Record<string, unknown> {
171
- const content = ResolveJsDocComment(node);
172
- return JsDoc.Parse(content);
173
- }
174
- // ------------------------------------------------------------------------------------------------------------
175
- // Identifiers
176
- // ------------------------------------------------------------------------------------------------------------
177
- function ResolveIdentifier(node: ts.InterfaceDeclaration | ts.TypeAliasDeclaration) {
178
- function* resolve(node: ts.Node): IterableIterator<string> {
179
- if (node.parent) yield* resolve(node.parent);
180
- if (ts.isModuleDeclaration(node)) yield node.name.getText();
181
- }
182
- return [...resolve(node), node.name.getText()].join('.');
183
- }
184
- function UnwrapModifier(type: string) {
185
- for (let i = 0; i < type.length; i++) if (type[i] === '(') return type.slice(i + 1, type.length - 1);
186
- return type;
187
- }
188
- // Note: This function is only called when 'useIdentifiers' is true. What we're trying to achieve with
189
- // identifier injection is a referential type model over the default inline model. For the purposes of
190
- // code generation, we tend to prefer referential types as these can be both inlined or referenced in
191
- // the codegen target; and where different targets may have different referential requirements. It
192
- // should be possible to implement a more robust injection mechanism however. For review.
193
- // prettier-ignore
194
- function InjectOptions(type: string, options: Record<string, unknown>): string {
195
- if (globalThis.Object.keys(options).length === 0) return type
196
- // unwrap for modifiers
197
- if (type.indexOf('Type.ReadonlyOptional') === 0) return `Type.ReadonlyOptional( ${InjectOptions(UnwrapModifier(type), options)} )`
198
- if (type.indexOf('Type.Readonly') === 0) return `Type.Readonly( ${InjectOptions(UnwrapModifier(type), options)} )`
199
- if (type.indexOf('Type.Optional') === 0) return `Type.Optional( ${InjectOptions(UnwrapModifier(type), options)} )`
200
- const encoded = JSON.stringify(options)
201
- // indexer type
202
- if (type.lastIndexOf(']') === type.length - 1) useCloneType = true
203
- if (type.lastIndexOf(']') === type.length - 1) return `CloneType(${type}, ${encoded})`
204
- // referenced type
205
- if (type.indexOf('(') === -1) { useCloneType = true; return `CloneType(${type}, ${encoded})` }
206
- if (type.lastIndexOf('()') === type.length - 2) return type.slice(0, type.length - 1) + `${encoded})`
207
- if (type.lastIndexOf('})') === type.length - 2) return type.slice(0, type.length - 1) + `, ${encoded})`
208
- if (type.lastIndexOf('])') === type.length - 2) return type.slice(0, type.length - 1) + `, ${encoded})`
209
- if (type.lastIndexOf(')') === type.length - 1) return type.slice(0, type.length - 1) + `, ${encoded})`
210
- return type
211
- }
212
- // ------------------------------------------------------------------------------------------------------------
213
- // Nodes
214
- // ------------------------------------------------------------------------------------------------------------
215
- function* SourceFile(node: ts.SourceFile): IterableIterator<string> {
216
- for (const next of node.getChildren()) {
217
- yield* Visit(next);
218
- }
219
- }
220
- function* PropertySignature(node: ts.PropertySignature): IterableIterator<string> {
221
- const [readonly, optional] = [IsReadonlyProperty(node), IsOptionalProperty(node)];
222
- const options = ResolveOptions(node);
223
- const type_0 = Collect(node.type);
224
- const type_1 = InjectOptions(type_0, options);
225
- if (readonly && optional) {
226
- return yield `${node.name.getText()}: Type.ReadonlyOptional(${type_1})`;
227
- } else if (readonly) {
228
- return yield `${node.name.getText()}: Type.Readonly(${type_1})`;
229
- } else if (optional) {
230
- return yield `${node.name.getText()}: Type.Optional(${type_1})`;
231
- } else {
232
- return yield `${node.name.getText()}: ${type_1}`;
233
- }
234
- }
235
- function* ArrayTypeNode(node: ts.ArrayTypeNode): IterableIterator<string> {
236
- const type = Collect(node.elementType);
237
- yield `Type.Array(${type})`;
238
- }
239
- function* Block(node: ts.Block): IterableIterator<string> {
240
- blockLevel += 1;
241
- const statments = node.statements.map((statement) => Collect(statement)).join('\n\n');
242
- blockLevel -= 1;
243
- yield `{\n${statments}\n}`;
244
- }
245
- function* TupleTypeNode(node: ts.TupleTypeNode): IterableIterator<string> {
246
- const types = node.elements.map((type) => Collect(type)).join(',\n');
247
- yield `Type.Tuple([\n${types}\n])`;
248
- }
249
- function* UnionTypeNode(node: ts.UnionTypeNode): IterableIterator<string> {
250
- const types = node.types.map((type) => Collect(type)).join(',\n');
251
- yield `Type.Union([\n${types}\n])`;
252
- }
253
- function* MappedTypeNode(node: ts.MappedTypeNode): IterableIterator<string> {
254
- const K = Collect(node.typeParameter);
255
- const T = Collect(node.type);
256
- const C = Collect(node.typeParameter.constraint);
257
- const readonly = node.readonlyToken !== undefined;
258
- const optional = node.questionToken !== undefined;
259
- const readonly_subtractive = readonly && ts.isMinusToken(node.readonlyToken);
260
- const optional_subtractive = optional && ts.isMinusToken(node.questionToken);
261
- // prettier-ignore
262
- return yield (
263
- (readonly && optional) ? (
264
- (readonly_subtractive && optional_subtractive) ? `Type.Mapped(${C}, ${K} => Type.Readonly(Type.Optional(${T}, false), false))` :
265
- (readonly_subtractive) ? `Type.Mapped(${C}, ${K} => Type.Readonly(Type.Optional(${T}), false))` :
266
- (optional_subtractive) ? `Type.Mapped(${C}, ${K} => Type.Readonly(Type.Optional(${T}, false)))` :
267
- `Type.Mapped(${C}, ${K} => Type.Readonly(Type.Optional(${T})))`
268
- ) : (readonly) ? (
269
- readonly_subtractive
270
- ? `Type.Mapped(${C}, ${K} => Type.Readonly(${T}, false))`
271
- : `Type.Mapped(${C}, ${K} => Type.Readonly(${T}))`
272
- ) : (optional) ? (
273
- optional_subtractive
274
- ? `Type.Mapped(${C}, ${K} => Type.Optional(${T}, false))`
275
- : `Type.Mapped(${C}, ${K} => Type.Optional(${T}))`
276
- ) : `Type.Mapped(${C}, ${K} => ${T})`
277
- )
278
- }
279
- function* MethodSignature(node: ts.MethodSignature): IterableIterator<string> {
280
- const parameters = node.parameters
281
- .map((parameter) =>
282
- parameter.dotDotDotToken !== undefined ? `...Type.Rest(${Collect(parameter)})` : Collect(parameter),
283
- )
284
- .join(', ');
285
- const returnType = node.type === undefined ? `Type.Unknown()` : Collect(node.type);
286
- yield `${node.name.getText()}: Type.Function([${parameters}], ${returnType})`;
287
- }
288
- // prettier-ignore
289
- function* TemplateLiteralTypeNode(node: ts.TemplateLiteralTypeNode) {
290
- const collect = node.getChildren().map(node => Collect(node)).join('')
291
- yield `Type.TemplateLiteral([${collect.slice(0, collect.length - 2)}])` // can't remove trailing here
292
- }
293
- // prettier-ignore
294
- function* TemplateLiteralTypeSpan(node: ts.TemplateLiteralTypeSpan) {
295
- const collect = node.getChildren().map(node => Collect(node)).join(', ')
296
- if (collect.length > 0) yield `${collect}`
297
- }
298
- function* TemplateHead(node: ts.TemplateHead) {
299
- if (node.text.length > 0) yield `Type.Literal('${node.text}'), `;
300
- }
301
- function* TemplateMiddle(node: ts.TemplateMiddle) {
302
- if (node.text.length > 0) yield `Type.Literal('${node.text}'), `;
303
- }
304
- function* TemplateTail(node: ts.TemplateTail) {
305
- if (node.text.length > 0) yield `Type.Literal('${node.text}'), `;
306
- }
307
- function* ThisTypeNode(node: ts.ThisTypeNode) {
308
- yield `This`;
309
- }
310
- function* IntersectionTypeNode(node: ts.IntersectionTypeNode): IterableIterator<string> {
311
- const types = node.types.map((type) => Collect(type)).join(',\n');
312
- yield `Type.Intersect([\n${types}\n])`;
313
- }
314
- function* TypeOperatorNode(node: ts.TypeOperatorNode): IterableIterator<string> {
315
- if (node.operator === ts.SyntaxKind.KeyOfKeyword) {
316
- const type = Collect(node.type);
317
- yield `Type.KeyOf(${type})`;
318
- }
319
- if (node.operator === ts.SyntaxKind.ReadonlyKeyword) {
320
- yield `Type.Readonly(${Collect(node.type)})`;
321
- }
322
- }
323
- function* Parameter(node: ts.ParameterDeclaration): IterableIterator<string> {
324
- yield Collect(node.type);
325
- }
326
- function* FunctionTypeNode(node: ts.FunctionTypeNode): IterableIterator<string> {
327
- const parameters = node.parameters
328
- .map((parameter) =>
329
- parameter.dotDotDotToken !== undefined ? `...Type.Rest(${Collect(parameter)})` : Collect(parameter),
330
- )
331
- .join(', ');
332
- const returns = Collect(node.type);
333
- yield `Type.Function([${parameters}], ${returns})`;
334
- }
335
- function* ConstructorTypeNode(node: ts.ConstructorTypeNode): IterableIterator<string> {
336
- const parameters = node.parameters.map((param) => Collect(param)).join(', ');
337
- const returns = Collect(node.type);
338
- yield `Type.Constructor([${parameters}], ${returns})`;
339
- }
340
- function* EnumDeclaration(node: ts.EnumDeclaration): IterableIterator<string> {
341
- useImports = true;
342
- const exports = IsExport(node) ? 'export ' : '';
343
- const members = node.members.map((member) => member.getText()).join(', ');
344
- const enumType = `${exports}enum Enum${node.name.getText()} { ${members} }`;
345
- const staticType = `${exports}type ${node.name.getText()} = Static<typeof ${node.name.getText()}>`;
346
- const type = `${exports}const ${node.name.getText()} = Type.Enum(Enum${node.name.getText()})`;
347
- yield [enumType, '', staticType, type].join('\n');
348
- }
349
- function PropertiesFromTypeElementArray(members: ts.NodeArray<ts.TypeElement>): string {
350
- const properties = members.filter((member) => !ts.isIndexSignatureDeclaration(member));
351
- const indexers = members.filter((member) => ts.isIndexSignatureDeclaration(member));
352
- const propertyCollect = properties.map((property) => Collect(property)).join(',\n');
353
- const indexer = indexers.length > 0 ? Collect(indexers[indexers.length - 1]) : '';
354
- if (properties.length === 0 && indexer.length > 0) {
355
- return `{},\n{\nadditionalProperties: ${indexer}\n }`;
356
- } else if (properties.length > 0 && indexer.length > 0) {
357
- return `{\n${propertyCollect}\n},\n{\nadditionalProperties: ${indexer}\n }`;
358
- } else {
359
- return `{\n${propertyCollect}\n}`;
360
- }
361
- }
362
- function* TypeLiteralNode(node: ts.TypeLiteralNode): IterableIterator<string> {
363
- const members = PropertiesFromTypeElementArray(node.members);
364
- yield* `Type.Object(${members})`;
365
- }
366
- function* InterfaceDeclaration(node: ts.InterfaceDeclaration): IterableIterator<string> {
367
- useImports = true;
368
- const isRecursiveType = IsRecursiveType(node);
369
- if (isRecursiveType) recursiveDeclaration = node;
370
- const heritage = node.heritageClauses !== undefined ? node.heritageClauses.flatMap((node) => Collect(node)) : [];
371
- if (node.typeParameters) {
372
- useGenerics = true;
373
- const exports = IsExport(node) ? 'export ' : '';
374
- const identifier = ResolveIdentifier(node);
375
- const options = useIdentifiers ? { ...ResolveOptions(node), $id: identifier } : { ...ResolveOptions(node) };
376
- const constraints = node.typeParameters.map((param) => `${Collect(param)} extends TSchema`).join(', ');
377
- const parameters = node.typeParameters.map((param) => `${Collect(param)}: ${Collect(param)}`).join(', ');
378
- const members = PropertiesFromTypeElementArray(node.members);
379
- // const names = node.typeParameters.map((param) => `${Collect(param)}`).join(', ')
380
- // const staticDeclaration = `${exports}type ${node.name.getText()}<${constraints}> = Static<ReturnType<typeof ${node.name.getText()}<${names}>>>`
381
- const rawTypeExpression = IsRecursiveType(node)
382
- ? `Type.Recursive(This => Type.Object(${members}))`
383
- : `Type.Object(${members})`;
384
- const typeExpression =
385
- heritage.length === 0 ? rawTypeExpression : `Type.Composite([${heritage.join(', ')}, ${rawTypeExpression}])`;
386
- const type = InjectOptions(typeExpression, options);
387
- const typeDeclaration = `${exports}const ${node.name.getText()} = <${constraints}>(${parameters}) => ${type}`;
388
- yield `${typeDeclaration}`;
389
- } else {
390
- const exports = IsExport(node) ? 'export ' : '';
391
- const identifier = ResolveIdentifier(node);
392
- const options = useIdentifiers ? { ...ResolveOptions(node), $id: identifier } : { ...ResolveOptions(node) };
393
- const members = PropertiesFromTypeElementArray(node.members);
394
- const staticDeclaration = `${exports}type ${node.name.getText()} = Static<typeof ${node.name.getText()}>`;
395
- const rawTypeExpression = IsRecursiveType(node)
396
- ? `Type.Recursive(This => Type.Object(${members}))`
397
- : `Type.Object(${members})`;
398
- const typeExpression =
399
- heritage.length === 0 ? rawTypeExpression : `Type.Composite([${heritage.join(', ')}, ${rawTypeExpression}])`;
400
- const type = InjectOptions(typeExpression, options);
401
- const typeDeclaration = `${exports}const ${node.name.getText()} = ${type}`;
402
- yield `${staticDeclaration}\n${typeDeclaration}`;
403
- }
404
- recursiveDeclaration = null;
405
- }
406
- function* TypeAliasDeclaration(node: ts.TypeAliasDeclaration): IterableIterator<string> {
407
- useImports = true;
408
- const isRecursiveType = IsRecursiveType(node);
409
- if (isRecursiveType) recursiveDeclaration = node;
410
- // Generics case
411
- if (node.typeParameters) {
412
- useGenerics = true;
413
- const exports = IsExport(node) ? 'export ' : '';
414
- const options = useIdentifiers ? { $id: ResolveIdentifier(node) } : {};
415
- const constraints = node.typeParameters.map((param) => `${Collect(param)} extends TSchema`).join(', ');
416
- const parameters = node.typeParameters.map((param) => `${Collect(param)}: ${Collect(param)}`).join(', ');
417
- const type_0 = Collect(node.type);
418
- const type_1 = isRecursiveType ? `Type.Recursive(This => ${type_0})` : type_0;
419
- const type_2 = InjectOptions(type_1, options);
420
- // const names = node.typeParameters.map((param) => Collect(param)).join(', ')
421
- // const staticDeclaration = `${exports}type ${node.name.getText()}<${constraints}> = Static<ReturnType<typeof ${node.name.getText()}<${names}>>>`
422
- const typeDeclaration = `${exports}const ${node.name.getText()} = <${constraints}>(${parameters}) => ${type_2}`;
423
- yield `${typeDeclaration}`;
424
- } else {
425
- const exports = IsExport(node) ? 'export ' : '';
426
- const options = useIdentifiers
427
- ? { $id: ResolveIdentifier(node), ...ResolveOptions(node) }
428
- : { ...ResolveOptions(node) };
429
- const type_0 = Collect(node.type);
430
- const type_1 = isRecursiveType ? `Type.Recursive(This => ${type_0})` : type_0;
431
- const type_2 = InjectOptions(type_1, options);
432
- const staticDeclaration = `${exports}type ${node.name.getText()} = Static<typeof ${node.name.getText()}>`;
433
- const typeDeclaration = `${exports}const ${node.name.getText()} = ${type_2}`;
434
- yield `${staticDeclaration}\n${typeDeclaration}`;
435
- }
436
- recursiveDeclaration = null;
437
- }
438
- function* HeritageClause(node: ts.HeritageClause): IterableIterator<string> {
439
- // Consideration: This may be better expressed as a heritage type (for review)
440
- const types = node.types.map((node) => Collect(node));
441
- if (types.length === 1) return yield types[0];
442
- // yield `Type.Composite([${types.join(', ')}])`
443
-
444
- // Note: Heritage clauses are only used in extends cases, and where Composite
445
- // is the exterior type. These types will be prepended to the Composite array.
446
- yield types.join(', ');
447
- }
448
- function* IndexedAccessType(node: ts.IndexedAccessTypeNode): IterableIterator<string> {
449
- const obj = node.objectType.getText();
450
- const key = Collect(node.indexType);
451
- yield `Type.Index(${obj}, ${key})`;
452
- }
453
- function* ExpressionWithTypeArguments(node: ts.ExpressionWithTypeArguments): IterableIterator<string> {
454
- const name = Collect(node.expression);
455
- const typeArguments = node.typeArguments === undefined ? [] : node.typeArguments.map((node) => Collect(node));
456
- // todo: default type argument (resolve `= number` from `type Foo<T = number>`)
457
- return yield typeArguments.length === 0 ? `${name}` : `${name}(${typeArguments.join(', ')})`;
458
- }
459
- function* TypeParameterDeclaration(node: ts.TypeParameterDeclaration): IterableIterator<string> {
460
- yield node.name.getText();
461
- }
462
- function* ParenthesizedTypeNode(node: ts.ParenthesizedTypeNode): IterableIterator<string> {
463
- yield Collect(node.type);
464
- }
465
- function* RestTypeNode(node: ts.RestTypeNode): IterableIterator<string> {
466
- yield `...Type.Rest(${node.type.getText()})`;
467
- }
468
- function* ConditionalTypeNode(node: ts.ConditionalTypeNode): IterableIterator<string> {
469
- const checkType = Collect(node.checkType);
470
- const extendsType = Collect(node.extendsType);
471
- const trueType = Collect(node.trueType);
472
- const falseType = Collect(node.falseType);
473
- yield `Type.Extends(${checkType}, ${extendsType}, ${trueType}, ${falseType})`;
474
- }
475
- function* isIndexSignatureDeclaration(node: ts.IndexSignatureDeclaration) {
476
- // note: we ignore the key and just return the type. this is a mismatch between
477
- // object and record types. Address in TypeBox by unifying validation paths
478
- // for objects and record types.
479
- yield Collect(node.type);
480
- }
481
- function* TypeReferenceNode(node: ts.TypeReferenceNode): IterableIterator<string> {
482
- const name = node.typeName.getText();
483
- const args = node.typeArguments ? `(${node.typeArguments.map((type) => Collect(type)).join(', ')})` : '';
484
- // --------------------------------------------------------------
485
- // Instance Types
486
- // --------------------------------------------------------------
487
- if (name === 'Date') return yield `Type.Date()`;
488
- if (name === 'Uint8Array') return yield `Type.Uint8Array()`;
489
- if (name === 'String') return yield `Type.String()`;
490
- if (name === 'Number') return yield `Type.Number()`;
491
- if (name === 'Boolean') return yield `Type.Boolean()`;
492
- if (name === 'Function') return yield `Type.Function([], Type.Unknown())`;
493
- // --------------------------------------------------------------
494
- // Types
495
- // --------------------------------------------------------------
496
- if (name === 'Array') return yield `Type.Array${args}`;
497
- if (name === 'Record') return yield `Type.Record${args}`;
498
- if (name === 'Partial') return yield `Type.Partial${args}`;
499
- if (name === 'Required') return yield `Type.Required${args}`;
500
- if (name === 'Omit') return yield `Type.Omit${args}`;
501
- if (name === 'Pick') return yield `Type.Pick${args}`;
502
- if (name === 'Promise') return yield `Type.Promise${args}`;
503
- if (name === 'ReturnType') return yield `Type.ReturnType${args}`;
504
- if (name === 'InstanceType') return yield `Type.InstanceType${args}`;
505
- if (name === 'Parameters') return yield `Type.Parameters${args}`;
506
- if (name === 'AsyncIterableIterator') return yield `Type.AsyncIterator${args}`;
507
- if (name === 'IterableIterator') return yield `Type.Iterator${args}`;
508
- if (name === 'ConstructorParameters') return yield `Type.ConstructorParameters${args}`;
509
- if (name === 'Exclude') return yield `Type.Exclude${args}`;
510
- if (name === 'Extract') return yield `Type.Extract${args}`;
511
- if (name === 'Awaited') return yield `Type.Awaited${args}`;
512
- if (name === 'Uppercase') return yield `Type.Uppercase${args}`;
513
- if (name === 'Lowercase') return yield `Type.Lowercase${args}`;
514
- if (name === 'Capitalize') return yield `Type.Capitalize${args}`;
515
- if (name === 'Uncapitalize') return yield `Type.Uncapitalize${args}`;
516
- if (recursiveDeclaration !== null && FindRecursiveParent(recursiveDeclaration, node)) return yield `This`;
517
- if (FindTypeName(node.getSourceFile(), name) && args.length === 0 /** non-resolvable */) {
518
- return yield `${name}${args}`;
519
- }
520
- if (name in globalThis) return yield `Type.Never()`;
521
- return yield `${name}${args}`;
522
- }
523
- function* LiteralTypeNode(node: ts.LiteralTypeNode): IterableIterator<string> {
524
- const text = node.getText();
525
- if (text === 'null') return yield `Type.Null()`;
526
- yield InjectOptions(`Type.Literal(${node.getText()})`, ResolveOptions(node));
527
- }
528
- function* ModuleDeclaration(node: ts.ModuleDeclaration): IterableIterator<string> {
529
- const export_specifier = IsExport(node) ? 'export ' : '';
530
- const module_specifier = IsNamespace(node) ? 'namespace' : 'module';
531
- yield `${export_specifier}${module_specifier} ${node.name.getText()} {`;
532
- yield* Visit(node.body);
533
- yield `}`;
534
- }
535
- function* ModuleBlock(node: ts.ModuleBlock): IterableIterator<string> {
536
- for (const statement of node.statements) {
537
- yield* Visit(statement);
538
- }
539
- }
540
- function* FunctionDeclaration(node: ts.FunctionDeclaration): IterableIterator<string> {
541
- // ignore
542
- }
543
- function* ClassDeclaration(node: ts.ClassDeclaration): IterableIterator<string> {
544
- // ignore
545
- }
546
- function Collect(node: ts.Node | undefined): string {
547
- return `${[...Visit(node)].join('')}`;
548
- }
549
- function* Visit(node: ts.Node | undefined): IterableIterator<string> {
550
- if (node === undefined) return;
551
- if (ts.isArrayTypeNode(node)) return yield* ArrayTypeNode(node);
552
- if (ts.isBlock(node)) return yield* Block(node);
553
- if (ts.isClassDeclaration(node)) return yield* ClassDeclaration(node);
554
- if (ts.isConditionalTypeNode(node)) return yield* ConditionalTypeNode(node);
555
- if (ts.isConstructorTypeNode(node)) return yield* ConstructorTypeNode(node);
556
- if (ts.isEnumDeclaration(node)) return yield* EnumDeclaration(node);
557
- if (ts.isExpressionWithTypeArguments(node)) return yield* ExpressionWithTypeArguments(node);
558
- if (ts.isFunctionDeclaration(node)) return yield* FunctionDeclaration(node);
559
- if (ts.isFunctionTypeNode(node)) return yield* FunctionTypeNode(node);
560
- if (ts.isHeritageClause(node)) return yield* HeritageClause(node);
561
- if (ts.isIndexedAccessTypeNode(node)) return yield* IndexedAccessType(node);
562
- if (ts.isIndexSignatureDeclaration(node)) return yield* isIndexSignatureDeclaration(node);
563
- if (ts.isInterfaceDeclaration(node)) return yield* InterfaceDeclaration(node);
564
- if (ts.isLiteralTypeNode(node)) return yield* LiteralTypeNode(node);
565
- if (ts.isPropertySignature(node)) return yield* PropertySignature(node);
566
- if (ts.isModuleDeclaration(node)) return yield* ModuleDeclaration(node);
567
- if (ts.isIdentifier(node)) return yield node.getText();
568
- if (ts.isIntersectionTypeNode(node)) return yield* IntersectionTypeNode(node);
569
- if (ts.isUnionTypeNode(node)) return yield* UnionTypeNode(node);
570
- if (ts.isMappedTypeNode(node)) return yield* MappedTypeNode(node);
571
- if (ts.isMethodSignature(node)) return yield* MethodSignature(node);
572
- if (ts.isModuleBlock(node)) return yield* ModuleBlock(node);
573
- if (ts.isParameter(node)) return yield* Parameter(node);
574
- if (ts.isParenthesizedTypeNode(node)) return yield* ParenthesizedTypeNode(node);
575
- if (ts.isRestTypeNode(node)) return yield* RestTypeNode(node);
576
- if (ts.isTupleTypeNode(node)) return yield* TupleTypeNode(node);
577
- if (ts.isTemplateLiteralTypeNode(node)) return yield* TemplateLiteralTypeNode(node);
578
- if (ts.isTemplateLiteralTypeSpan(node)) return yield* TemplateLiteralTypeSpan(node);
579
- if (ts.isTemplateHead(node)) return yield* TemplateHead(node);
580
- if (ts.isTemplateMiddle(node)) return yield* TemplateMiddle(node);
581
- if (ts.isTemplateTail(node)) return yield* TemplateTail(node);
582
- if (ts.isThisTypeNode(node)) return yield* ThisTypeNode(node);
583
- if (ts.isTypeAliasDeclaration(node)) return yield* TypeAliasDeclaration(node);
584
- if (ts.isTypeLiteralNode(node)) return yield* TypeLiteralNode(node);
585
- if (ts.isTypeOperatorNode(node)) return yield* TypeOperatorNode(node);
586
- if (ts.isTypeParameterDeclaration(node)) return yield* TypeParameterDeclaration(node);
587
- if (ts.isTypeReferenceNode(node)) return yield* TypeReferenceNode(node);
588
- if (ts.isSourceFile(node)) return yield* SourceFile(node);
589
- if (node.kind === ts.SyntaxKind.ExportKeyword) return yield `export`;
590
- if (node.kind === ts.SyntaxKind.KeyOfKeyword) return yield `Type.KeyOf()`;
591
- if (node.kind === ts.SyntaxKind.NumberKeyword) return yield `Type.Number()`;
592
- if (node.kind === ts.SyntaxKind.BigIntKeyword) return yield `Type.BigInt()`;
593
- if (node.kind === ts.SyntaxKind.StringKeyword) return yield `Type.String()`;
594
- if (node.kind === ts.SyntaxKind.SymbolKeyword) return yield `Type.Symbol()`;
595
- if (node.kind === ts.SyntaxKind.BooleanKeyword) return yield `Type.Boolean()`;
596
- if (node.kind === ts.SyntaxKind.UndefinedKeyword) return yield `Type.Undefined()`;
597
- if (node.kind === ts.SyntaxKind.UnknownKeyword) return yield `Type.Unknown()`;
598
- if (node.kind === ts.SyntaxKind.AnyKeyword) return yield `Type.Any()`;
599
- if (node.kind === ts.SyntaxKind.NeverKeyword) return yield `Type.Never()`;
600
- if (node.kind === ts.SyntaxKind.NullKeyword) return yield `Type.Null()`;
601
- if (node.kind === ts.SyntaxKind.VoidKeyword) return yield `Type.Void()`;
602
- if (node.kind === ts.SyntaxKind.EndOfFileToken) return;
603
- if (node.kind === ts.SyntaxKind.SyntaxList) {
604
- for (const child of node.getChildren()) {
605
- yield* Visit(child);
606
- }
607
- return;
608
- }
609
- console.warn('Unhandled:', ts.SyntaxKind[node.kind], node.getText());
610
- }
611
- function ImportStatement(): string {
612
- if (!(useImports && useTypeBoxImport)) return '';
613
- const set = new Set<string>(['Type', 'Static']);
614
- if (useGenerics) {
615
- set.add('TSchema');
616
- }
617
- if (useOptions) {
618
- set.add('SchemaOptions');
619
- }
620
- if (useCloneType) {
621
- set.add('CloneType');
622
- }
623
- const imports = [...set].join(', ');
624
- return `import { ${imports} } from '@sinclair/typebox'`;
625
- }
626
- /** Generates TypeBox types from TypeScript interface and type definitions */
627
- export function Generate(typescriptCode: string, options?: TypeScriptToTypeBoxOptions) {
628
- useExportsEverything = options?.useExportEverything ?? false;
629
- useIdentifiers = options?.useIdentifiers ?? false;
630
- useTypeBoxImport = options?.useTypeBoxImport ?? true;
631
- typenames.clear();
632
- useImports = false;
633
- useOptions = false;
634
- useGenerics = false;
635
- useCloneType = false;
636
- blockLevel = 0;
637
- const source = ts.createSourceFile('types.ts', typescriptCode, ts.ScriptTarget.ESNext, true);
638
- const declarations = [...Visit(source)].join('\n\n');
639
- const imports = ImportStatement();
640
- const typescript = [imports, '', '', declarations].join('\n');
641
- const assertion = ts.transpileModule(typescript, transpilerOptions);
642
- if (assertion.diagnostics && assertion.diagnostics.length > 0) {
643
- throw new TypeScriptToTypeBoxError(assertion.diagnostics);
644
- }
645
- return typescript;
646
- }
647
- }
@@ -1,12 +0,0 @@
1
- import { TypeGen } from '.';
2
- import { test } from 'vitest';
3
-
4
- test('type gen', () => {
5
- console.log(
6
- TypeGen.TypeScriptToTypeBox.Generate(`
7
- interface HI {
8
- name: string
9
- }
10
- `),
11
- );
12
- });
@@ -1 +0,0 @@
1
- export * as TypeGen from './codegen';
File without changes