nucleus-core-ts 0.10.147 → 0.10.151

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 (204) hide show
  1. package/LICENSE +48 -48
  2. package/dist/.build-ok +1 -1
  3. package/dist/fe/components/AuthorizationPage/labels.js +13 -13
  4. package/dist/fe/components/Captcha/labels.js +17 -17
  5. package/dist/fe/components/ChatPanel/helpers.js +17 -17
  6. package/dist/fe/components/ChatPanel/labels.js +16 -16
  7. package/dist/fe/components/DataTable/labels.js +16 -16
  8. package/dist/fe/components/DevicesPage/components/DeviceCard.js +15 -15
  9. package/dist/fe/components/DevicesPage/components/DevicesPage.js +9 -9
  10. package/dist/fe/components/DevicesPage/labels.js +12 -12
  11. package/dist/fe/components/ForgotPasswordPage/labels.js +8 -8
  12. package/dist/fe/components/FormBuilder/components/FormField.js +5 -5
  13. package/dist/fe/components/FormBuilder/utils/fieldMapping.js +9 -9
  14. package/dist/fe/components/IntegrationsPage/components/ConnectionAuthFields.js +8 -8
  15. package/dist/fe/components/IntegrationsPage/components/ConnectionBasicFields.js +3 -3
  16. package/dist/fe/components/IntegrationsPage/components/ConnectionExport.js +23 -23
  17. package/dist/fe/components/IntegrationsPage/components/ConnectionForm.js +22 -22
  18. package/dist/fe/components/IntegrationsPage/components/ConnectionList.js +7 -7
  19. package/dist/fe/components/IntegrationsPage/components/ConnectionOauthFields.js +6 -6
  20. package/dist/fe/components/IntegrationsPage/components/ConnectionSettingsTab.js +24 -24
  21. package/dist/fe/components/IntegrationsPage/components/ConnectionSwitcher.js +19 -19
  22. package/dist/fe/components/IntegrationsPage/components/ConnectionTabs.js +15 -15
  23. package/dist/fe/components/IntegrationsPage/components/ConnectionTest.js +21 -21
  24. package/dist/fe/components/IntegrationsPage/components/ConnectionTransfer.js +18 -18
  25. package/dist/fe/components/IntegrationsPage/components/CredentialFields.js +19 -19
  26. package/dist/fe/components/IntegrationsPage/components/CredentialSlotRow.js +8 -8
  27. package/dist/fe/components/IntegrationsPage/components/EndpointForm.js +7 -7
  28. package/dist/fe/components/IntegrationsPage/components/EndpointFormFields.js +12 -12
  29. package/dist/fe/components/IntegrationsPage/components/EndpointList.js +7 -7
  30. package/dist/fe/components/IntegrationsPage/components/EndpointSample.js +36 -36
  31. package/dist/fe/components/IntegrationsPage/components/EndpointsTab.js +29 -29
  32. package/dist/fe/components/IntegrationsPage/components/FieldMappingRow.js +7 -7
  33. package/dist/fe/components/IntegrationsPage/components/FieldMappingRows.js +6 -6
  34. package/dist/fe/components/IntegrationsPage/components/IntegrationsPage.js +60 -60
  35. package/dist/fe/components/IntegrationsPage/components/MappingAccountFields.js +15 -15
  36. package/dist/fe/components/IntegrationsPage/components/MappingEditor.js +9 -9
  37. package/dist/fe/components/IntegrationsPage/components/MappingList.js +23 -23
  38. package/dist/fe/components/IntegrationsPage/components/MappingPasswordField.js +12 -12
  39. package/dist/fe/components/IntegrationsPage/components/MappingScheduleFields.js +23 -23
  40. package/dist/fe/components/IntegrationsPage/components/MappingWriteModeFields.js +31 -31
  41. package/dist/fe/components/IntegrationsPage/components/MappingsTab.js +56 -56
  42. package/dist/fe/components/IntegrationsPage/components/PaginationFields.js +11 -11
  43. package/dist/fe/components/IntegrationsPage/components/ParamBindingRows.js +15 -15
  44. package/dist/fe/components/IntegrationsPage/components/Primitives.js +28 -28
  45. package/dist/fe/components/IntegrationsPage/components/ReferenceCheckRows.js +9 -9
  46. package/dist/fe/components/IntegrationsPage/components/RunConfirmStep.js +6 -6
  47. package/dist/fe/components/IntegrationsPage/components/RunHistory.js +6 -6
  48. package/dist/fe/components/IntegrationsPage/components/RunHistoryRow.js +9 -9
  49. package/dist/fe/components/IntegrationsPage/components/RunPanel.js +40 -40
  50. package/dist/fe/components/IntegrationsPage/components/RunPasswordField.js +18 -18
  51. package/dist/fe/components/IntegrationsPage/components/RunPlanIssues.js +6 -6
  52. package/dist/fe/components/IntegrationsPage/components/RunPlanReferences.js +12 -12
  53. package/dist/fe/components/IntegrationsPage/components/RunPlanSuggestions.js +11 -11
  54. package/dist/fe/components/IntegrationsPage/components/RunPlanSummary.js +6 -6
  55. package/dist/fe/components/IntegrationsPage/components/RunProgressBar.js +6 -6
  56. package/dist/fe/components/IntegrationsPage/components/RunRevertConflicts.js +6 -6
  57. package/dist/fe/components/IntegrationsPage/components/Skeletons.js +7 -7
  58. package/dist/fe/components/IntegrationsPage/components/authOptions.js +4 -4
  59. package/dist/fe/components/IntegrationsPage/components/connectionDraft.js +27 -27
  60. package/dist/fe/components/IntegrationsPage/components/credentialSlots.js +25 -25
  61. package/dist/fe/components/IntegrationsPage/components/deleteIsConfirmed.js +9 -9
  62. package/dist/fe/components/IntegrationsPage/components/fieldMappingOptions.js +4 -4
  63. package/dist/fe/components/IntegrationsPage/components/formSupport.js +34 -34
  64. package/dist/fe/components/IntegrationsPage/components/jsonArray.js +14 -14
  65. package/dist/fe/components/IntegrationsPage/components/jsonObjectField.js +15 -15
  66. package/dist/fe/components/IntegrationsPage/components/mappingDraft.js +10 -10
  67. package/dist/fe/components/IntegrationsPage/components/mappingStaleness.js +22 -22
  68. package/dist/fe/components/IntegrationsPage/components/nextRuns.js +8 -8
  69. package/dist/fe/components/IntegrationsPage/components/passwordIsNeeded.js +13 -13
  70. package/dist/fe/components/IntegrationsPage/components/pathParams.js +6 -6
  71. package/dist/fe/components/IntegrationsPage/components/runFormat.js +18 -18
  72. package/dist/fe/components/IntegrationsPage/components/settleOwnership.js +18 -18
  73. package/dist/fe/components/IntegrationsPage/components/useInfiniteList.js +8 -8
  74. package/dist/fe/components/IntegrationsPage/store/index.js +20 -20
  75. package/dist/fe/components/IntegrationsPage/store/upsertInto.js +12 -12
  76. package/dist/fe/components/IntegrationsPage/text/context.js +6 -6
  77. package/dist/fe/components/IntegrationsPage/text/index.js +18 -18
  78. package/dist/fe/components/IntegrationsPage/theme/index.js +29 -29
  79. package/dist/fe/components/IntegrationsPage/types/records.js +10 -10
  80. package/dist/fe/components/IntegrationsPage/types/results.js +3 -3
  81. package/dist/fe/components/NotificationCenter/labels.js +17 -17
  82. package/dist/fe/components/ProfilePage/labels.js +10 -10
  83. package/dist/fe/components/ResetPasswordPage/labels.js +4 -4
  84. package/dist/fe/components/SetPasswordPage/labels.js +11 -11
  85. package/dist/fe/components/UsersPage/labels.js +14 -14
  86. package/dist/fe/utils/columnUtils.js +24 -24
  87. package/dist/fe/utils/searchFold.js +36 -36
  88. package/dist/index.js +6 -6
  89. package/dist/server.js +6 -6
  90. package/dist/src/Client/Proxy/authz.js +4 -4
  91. package/dist/src/Client/Proxy/httpProxy.js +136 -136
  92. package/dist/src/Client/Proxy/largeBody.js +29 -29
  93. package/dist/src/Client/Proxy/utils.js +32 -32
  94. package/dist/src/Client/Proxy/wsProxy.js +59 -59
  95. package/dist/src/Managers/Redis/index.d.ts +14 -0
  96. package/dist/src/Nucleus/routes/auth/admin/impersonationStore.d.ts +3 -4
  97. package/dist/src/Nucleus/routes/auth/refresh/issuedPair.d.ts +67 -0
  98. package/dist/src/Nucleus/routes/auth/refresh/recordIssued.d.ts +15 -6
  99. package/dist/src/Nucleus/routes/auth/refresh/refreshChain.d.ts +56 -0
  100. package/dist/src/Services/Auth/SessionStore/utils.d.ts +2 -0
  101. package/dist/src/Shared/cron.js +71 -71
  102. package/dist/src/Shared/redactSecrets.js +156 -156
  103. package/dist/src/Shared/redaction/bare.js +61 -61
  104. package/dist/src/Shared/redaction/floor.js +48 -48
  105. package/dist/src/Shared/redaction/freeText.js +70 -70
  106. package/dist/src/Shared/redaction/json.js +30 -30
  107. package/dist/src/Shared/redaction/lists.js +23 -23
  108. package/dist/src/Shared/redaction/markers.js +28 -28
  109. package/dist/src/Shared/redaction/names.js +49 -49
  110. package/dist/src/Shared/redaction/pairs.js +54 -54
  111. package/dist/src/Shared/redaction/secretString.js +29 -29
  112. package/dist/src/Shared/redaction/structured.js +52 -52
  113. package/dist/src/Shared/redaction/walk.js +25 -25
  114. package/infra/scripts/generate-project.ts +766 -766
  115. package/infra/templates/README.md +57 -57
  116. package/infra/templates/backend/.dockerignore +9 -9
  117. package/infra/templates/backend/.env.example +15 -15
  118. package/infra/templates/backend/README.md +28 -28
  119. package/infra/templates/backend/azure-pipelines.yml +135 -135
  120. package/infra/templates/backend/k8s/Dockerfile +31 -31
  121. package/infra/templates/backend/k8s/configmap.yaml +26 -26
  122. package/infra/templates/backend/k8s/deployment.yaml +85 -85
  123. package/infra/templates/backend/k8s/pvc.yaml +12 -12
  124. package/infra/templates/backend/k8s/service.yaml +13 -13
  125. package/infra/templates/backend/tsconfig.json +22 -22
  126. package/infra/templates/frontend/.dockerignore +10 -10
  127. package/infra/templates/frontend/.env.example +8 -8
  128. package/infra/templates/frontend/.env.local.example +10 -10
  129. package/infra/templates/frontend/README.md +69 -69
  130. package/infra/templates/frontend/app/[tablename]/page.tsx +37 -37
  131. package/infra/templates/frontend/app/_components/AuthWrapper/index.tsx +63 -63
  132. package/infra/templates/frontend/app/authorization/page.tsx +43 -43
  133. package/infra/templates/frontend/app/change-password/page.tsx +23 -23
  134. package/infra/templates/frontend/app/devices/page.tsx +127 -127
  135. package/infra/templates/frontend/app/forgot-password/page.tsx +20 -20
  136. package/infra/templates/frontend/app/globals.css +28 -28
  137. package/infra/templates/frontend/app/layout.tsx +35 -35
  138. package/infra/templates/frontend/app/login/page.tsx +33 -33
  139. package/infra/templates/frontend/app/page.tsx +565 -565
  140. package/infra/templates/frontend/app/profile/page.tsx +92 -92
  141. package/infra/templates/frontend/app/register/page.tsx +27 -27
  142. package/infra/templates/frontend/app/reset-password/page.tsx +60 -60
  143. package/infra/templates/frontend/app/set-password/page.tsx +43 -43
  144. package/infra/templates/frontend/app/ui-docs/page.tsx +52 -52
  145. package/infra/templates/frontend/app/users/page.tsx +52 -52
  146. package/infra/templates/frontend/app/verify-email/page.tsx +41 -41
  147. package/infra/templates/frontend/app/verify-magic-link/page.tsx +46 -46
  148. package/infra/templates/frontend/azure-pipelines.yml +137 -137
  149. package/infra/templates/frontend/code-and-design-principles.md +438 -438
  150. package/infra/templates/frontend/k8s/Dockerfile +50 -50
  151. package/infra/templates/frontend/k8s/configmap.yaml +18 -18
  152. package/infra/templates/frontend/k8s/deployment.yaml +72 -72
  153. package/infra/templates/frontend/k8s/ingress.yaml +36 -36
  154. package/infra/templates/frontend/k8s/service.yaml +14 -14
  155. package/infra/templates/frontend/lib/api/endpoints.ts +37 -37
  156. package/infra/templates/frontend/lib/api/factory.ts +44 -44
  157. package/infra/templates/frontend/lib/api/hook.ts +10 -10
  158. package/infra/templates/frontend/next.config.ts +19 -19
  159. package/infra/templates/frontend/package.json +34 -34
  160. package/infra/templates/frontend/postcss.config.mjs +5 -5
  161. package/infra/templates/frontend/server.ts +114 -114
  162. package/infra/templates/frontend/tsconfig.json +23 -23
  163. package/package.json +1 -1
  164. package/public/components/CTA.tsx +25 -25
  165. package/public/components/Capabilities.tsx +67 -67
  166. package/public/components/Features.tsx +107 -107
  167. package/public/components/Footer.tsx +58 -58
  168. package/public/components/Hero.tsx +51 -51
  169. package/public/components/Managers.tsx +55 -55
  170. package/public/components/Nav.tsx +91 -91
  171. package/public/components/Stack.tsx +36 -36
  172. package/public/components/docs/Docs.tsx +60 -60
  173. package/public/components/docs/DocsContent.tsx +176 -176
  174. package/public/components/docs/DocsRightSidebar.tsx +53 -53
  175. package/public/components/docs/DocsSidebar.tsx +54 -54
  176. package/public/components/docs/content/authentication.ts +836 -836
  177. package/public/components/docs/content/authorization.ts +268 -268
  178. package/public/components/docs/content/backupRestore.ts +173 -173
  179. package/public/components/docs/content/clientModule.ts +287 -287
  180. package/public/components/docs/content/entityCrud.ts +682 -682
  181. package/public/components/docs/content/monitoring.ts +313 -313
  182. package/public/components/docs/content/multiTenant.ts +269 -269
  183. package/public/components/docs/content/oauthApiKeys.ts +325 -325
  184. package/public/components/docs/content/pubsub.ts +131 -131
  185. package/public/components/docs/content/storageCdn.ts +171 -171
  186. package/public/components/docs/content/verification.ts +289 -289
  187. package/public/components/docs/docsData.ts +113 -113
  188. package/public/components/docs/index.ts +6 -6
  189. package/public/components/index.ts +9 -9
  190. package/public/docs.css +629 -629
  191. package/public/index.html +81 -81
  192. package/public/index.tsx +42 -42
  193. package/public/store.ts +76 -76
  194. package/public/styles.css +858 -858
  195. package/schemas/config.nucleus.json +2651 -2651
  196. package/scripts/audit-purge-noise.ts +120 -120
  197. package/scripts/build.ts +582 -582
  198. package/scripts/generate-system-tables-types.ts +18 -18
  199. package/scripts/generate-types-schema.test.ts +73 -73
  200. package/scripts/generate-types-schema.ts +1284 -1284
  201. package/scripts/packagedScripts.test.ts +87 -87
  202. package/scripts/publish.ts +276 -276
  203. package/scripts/skillCitations.test.ts +107 -107
  204. package/scripts/verify-publishable.ts +40 -40
@@ -1,1284 +1,1284 @@
1
- #!/usr/bin/env bun
2
- /**
3
- * Fully automated JSON Schema generator from TypeScript types in src/types.ts.
4
- * Recursively parses type aliases, interfaces, inline object types, unions,
5
- * arrays, Record<K,V>, Partial<T>, and imported type references.
6
- *
7
- * Run: bun run scripts/generate-types-schema.ts
8
- */
9
-
10
- import * as fs from 'node:fs'
11
- import * as path from 'node:path'
12
-
13
- const TYPES_FILE = path.resolve(import.meta.dir, '../src/types.ts')
14
- const SCHEMAS_DIR = path.resolve(import.meta.dir, '../schemas')
15
-
16
- // ---------------------------------------------------------------------------
17
- // Schema types
18
- // ---------------------------------------------------------------------------
19
- type SchemaNode = {
20
- type?: string | string[]
21
- description?: string
22
- enum?: string[]
23
- items?: SchemaNode
24
- properties?: Record<string, SchemaNode>
25
- required?: string[]
26
- default?: unknown
27
- $ref?: string
28
- additionalProperties?: boolean | SchemaNode
29
- minLength?: number
30
- maxLength?: number
31
- minimum?: number
32
- maximum?: number
33
- oneOf?: SchemaNode[]
34
- anyOf?: SchemaNode[]
35
- }
36
-
37
- type JsonSchema = {
38
- $id?: string
39
- $schema?: string
40
- title?: string
41
- description?: string
42
- type?: string
43
- properties?: Record<string, SchemaNode>
44
- required?: string[]
45
- $defs?: Record<string, SchemaNode>
46
- additionalProperties?: boolean
47
- }
48
-
49
- // ---------------------------------------------------------------------------
50
- // Source loader – loads types.ts + resolves imported type files
51
- // ---------------------------------------------------------------------------
52
- type SourceFile = { path: string; content: string }
53
-
54
- const PROJECT_ROOT = path.resolve(import.meta.dir, '..')
55
-
56
- function resolveModulePath(fromFile: string, modulePath: string): string | null {
57
- // Try relative resolution first
58
- const relCandidates = [
59
- path.resolve(path.dirname(fromFile), `${modulePath}.ts`),
60
- path.resolve(path.dirname(fromFile), modulePath, 'index.ts'),
61
- path.resolve(path.dirname(fromFile), modulePath, 'types.ts'),
62
- ]
63
- for (const c of relCandidates) {
64
- if (fs.existsSync(c)) return c
65
- }
66
-
67
- // Try tsconfig baseUrl resolution (baseUrl: ".")
68
- const baseCandidates = [
69
- path.resolve(PROJECT_ROOT, `${modulePath}.ts`),
70
- path.resolve(PROJECT_ROOT, modulePath, 'index.ts'),
71
- path.resolve(PROJECT_ROOT, modulePath, 'types.ts'),
72
- ]
73
- for (const c of baseCandidates) {
74
- if (fs.existsSync(c)) return c
75
- }
76
-
77
- return null
78
- }
79
-
80
- function collectExportedFiles(filePath: string, visited: Set<string>): SourceFile[] {
81
- if (visited.has(filePath)) return []
82
- visited.add(filePath)
83
-
84
- const content = fs.readFileSync(filePath, 'utf-8')
85
- const results: SourceFile[] = [{ path: filePath, content }]
86
-
87
- // Follow `export * from './...'` re-exports
88
- const reExportRegex = /export\s+\*\s+from\s+['"]([^'"]+)['"]/g
89
- let rem: RegExpExecArray | null = reExportRegex.exec(content)
90
- while (rem !== null) {
91
- const reExportPath = rem[1]
92
- if (reExportPath) {
93
- const resolved = resolveModulePath(filePath, reExportPath)
94
- if (resolved) {
95
- results.push(...collectExportedFiles(resolved, visited))
96
- }
97
- }
98
- rem = reExportRegex.exec(content)
99
- }
100
-
101
- return results
102
- }
103
-
104
- function loadSources(): SourceFile[] {
105
- const main = fs.readFileSync(TYPES_FILE, 'utf-8')
106
- const visited = new Set<string>([TYPES_FILE])
107
- const sources: SourceFile[] = [{ path: TYPES_FILE, content: main }]
108
-
109
- // Resolve imports from the main types file
110
- const importRegex = /import\s+(?:type\s+)?{([^}]+)}\s+from\s+['"]([^'"]+)['"]/g
111
- let m: RegExpExecArray | null = importRegex.exec(main)
112
- while (m !== null) {
113
- const modulePath = m[2]
114
- if (!modulePath || modulePath.startsWith('node:')) {
115
- m = importRegex.exec(main)
116
- continue
117
- }
118
- const resolved = resolveModulePath(TYPES_FILE, modulePath)
119
- if (resolved) {
120
- sources.push(...collectExportedFiles(resolved, visited))
121
- }
122
- m = importRegex.exec(main)
123
- }
124
-
125
- return sources
126
- }
127
-
128
- // ---------------------------------------------------------------------------
129
- // Tokenizer – splits TS source into a stream of meaningful tokens
130
- // ---------------------------------------------------------------------------
131
- type Token = {
132
- kind: 'word' | 'string' | 'number' | 'symbol' | 'comment' | 'multiline_comment'
133
- value: string
134
- pos: number
135
- }
136
-
137
- function tokenize(source: string): Token[] {
138
- const tokens: Token[] = []
139
- let i = 0
140
- const len = source.length
141
-
142
- while (i < len) {
143
- // Skip whitespace
144
- if (/\s/.test(source[i] as string)) {
145
- i++
146
- continue
147
- }
148
-
149
- // Single-line comment
150
- if (source[i] === '/' && source[i + 1] === '/') {
151
- const start = i
152
- while (i < len && source[i] !== '\n') i++
153
- tokens.push({ kind: 'comment', value: source.slice(start, i), pos: start })
154
- continue
155
- }
156
-
157
- // Multi-line comment / JSDoc
158
- if (source[i] === '/' && source[i + 1] === '*') {
159
- const start = i
160
- i += 2
161
- while (i < len - 1 && !(source[i] === '*' && source[i + 1] === '/')) i++
162
- i += 2
163
- tokens.push({ kind: 'multiline_comment', value: source.slice(start, i), pos: start })
164
- continue
165
- }
166
-
167
- // String literal
168
- if (source[i] === "'" || source[i] === '"' || source[i] === '`') {
169
- const quote = source[i]
170
- const start = i
171
- i++
172
- while (i < len && source[i] !== quote) {
173
- if (source[i] === '\\') i++
174
- i++
175
- }
176
- i++ // closing quote
177
- tokens.push({ kind: 'string', value: source.slice(start, i), pos: start })
178
- continue
179
- }
180
-
181
- // Number
182
- if (/[0-9]/.test(source[i] as string)) {
183
- const start = i
184
- while (i < len && /[0-9.]/.test(source[i] as string)) i++
185
- tokens.push({ kind: 'number', value: source.slice(start, i), pos: start })
186
- continue
187
- }
188
-
189
- // Word (identifier / keyword)
190
- if (/[a-zA-Z_$]/.test(source[i] as string)) {
191
- const start = i
192
- while (i < len && /[a-zA-Z0-9_$]/.test(source[i] as string)) i++
193
- tokens.push({ kind: 'word', value: source.slice(start, i), pos: start })
194
- continue
195
- }
196
-
197
- // Symbols
198
- tokens.push({ kind: 'symbol', value: source[i] as string, pos: i })
199
- i++
200
- }
201
-
202
- return tokens
203
- }
204
-
205
- // ---------------------------------------------------------------------------
206
- // Type registry – collects all exported types / interfaces from all sources
207
- // ---------------------------------------------------------------------------
208
- type ParsedProperty = {
209
- name: string
210
- optional: boolean
211
- typeExpr: TypeExpr
212
- description?: string
213
- }
214
-
215
- type TypeExpr =
216
- | { kind: 'primitive'; value: 'string' | 'number' | 'boolean' | 'unknown' | 'any' }
217
- | { kind: 'literal'; value: string } // e.g. 'HS256'
218
- | { kind: 'union'; members: TypeExpr[] }
219
- | { kind: 'array'; element: TypeExpr }
220
- | { kind: 'object'; properties: ParsedProperty[]; indexSignature?: TypeExpr }
221
- | { kind: 'record'; valueType: TypeExpr }
222
- | { kind: 'partial'; inner: TypeExpr }
223
- | { kind: 'reference'; name: string }
224
- | { kind: 'tuple'; elements: TypeExpr[] }
225
-
226
- type TypeDef = {
227
- name: string
228
- expr: TypeExpr
229
- description?: string
230
- }
231
-
232
- // ---------------------------------------------------------------------------
233
- // Token-stream parser
234
- // ---------------------------------------------------------------------------
235
- class TypeParser {
236
- private tokens: Token[]
237
- private pos: number
238
- private defs: Map<string, TypeDef> = new Map()
239
-
240
- constructor(sources: SourceFile[]) {
241
- this.tokens = []
242
- this.pos = 0
243
- for (const src of sources) {
244
- this.tokens.push(...tokenize(src.content))
245
- }
246
- this.parse()
247
- }
248
-
249
- getDefinition(name: string): TypeDef | undefined {
250
- return this.defs.get(name)
251
- }
252
-
253
- getAllDefs(): Map<string, TypeDef> {
254
- return this.defs
255
- }
256
-
257
- // -- Helpers ---------------------------------------------------------------
258
-
259
- private peek(offset = 0): Token | undefined {
260
- return this.tokens[this.pos + offset]
261
- }
262
-
263
- private advance(): Token {
264
- const t = this.tokens[this.pos]
265
- this.pos++
266
- return t as Token
267
- }
268
-
269
- private expect(kind: Token['kind'], value?: string): Token {
270
- const t = this.advance()
271
- if (!t || t.kind !== kind || (value !== undefined && t.value !== value)) {
272
- throw new Error(
273
- `Expected ${kind}${value ? ` '${value}'` : ''} at pos ${this.pos - 1}, got ${t?.kind} '${t?.value}'`
274
- )
275
- }
276
- return t
277
- }
278
-
279
- private match(kind: Token['kind'], value?: string): boolean {
280
- const t = this.peek()
281
- if (t && t.kind === kind && (value === undefined || t.value === value)) {
282
- this.advance()
283
- return true
284
- }
285
- return false
286
- }
287
-
288
- private is(kind: Token['kind'], value?: string): boolean {
289
- const t = this.peek()
290
- return !!t && t.kind === kind && (value === undefined || t.value === value)
291
- }
292
-
293
- /**
294
- * Index of the next token that is not a comment, starting at `from`.
295
- *
296
- * Comments are kept in the token stream because property descriptions are read
297
- * out of it, so the type-expression parser has to step over them explicitly.
298
- */
299
- private nextMeaningful(from: number): number {
300
- let i = from
301
- while (
302
- this.tokens[i] &&
303
- (this.tokens[i]?.kind === 'comment' || this.tokens[i]?.kind === 'multiline_comment')
304
- ) {
305
- i++
306
- }
307
- return i
308
- }
309
-
310
- /** Like `is`, but tolerates comments sitting in front of the token. */
311
- private isMeaningful(kind: Token['kind'], value?: string): boolean {
312
- const t = this.tokens[this.nextMeaningful(this.pos)]
313
- return !!t && t.kind === kind && (value === undefined || t.value === value)
314
- }
315
-
316
- /**
317
- * Like `match`, but tolerates comments in front of the token — and only consumes
318
- * them when the token actually matches.
319
- *
320
- * That conditional consumption is the whole point. A union member may carry its
321
- * own JSDoc (`| string[] /** … *\/ | string`), and without stepping over it the
322
- * parser saw a comment where it expected `|`, ended the union early and desynced
323
- * for the rest of the file — silently dropping every later property. Consuming
324
- * comments UNCONDITIONALLY would be just as wrong the other way: the comment
325
- * after a non-union property belongs to the NEXT property and is its description.
326
- */
327
- private matchMeaningful(kind: Token['kind'], value?: string): boolean {
328
- const i = this.nextMeaningful(this.pos)
329
- const t = this.tokens[i]
330
- if (t && t.kind === kind && (value === undefined || t.value === value)) {
331
- this.pos = i + 1
332
- return true
333
- }
334
- return false
335
- }
336
-
337
- /** Step over comments that sit directly before a type atom. */
338
- private skipCommentsBeforeType(): void {
339
- this.pos = this.nextMeaningful(this.pos)
340
- }
341
-
342
- private collectJSDoc(): string | undefined {
343
- // Look backwards from current pos for a preceding JSDoc comment
344
- let idx = this.pos - 1
345
- while (idx >= 0) {
346
- const t = this.tokens[idx]
347
- if (!t) break
348
- if (t.kind === 'multiline_comment' && t.value.startsWith('/**')) {
349
- // Extract text from JSDoc
350
- return (
351
- t.value
352
- .replace(/^\/\*\*\s*/, '')
353
- .replace(/\s*\*\/$/, '')
354
- .split('\n')
355
- .map((l) => l.replace(/^\s*\*\s?/, '').trim())
356
- .filter((l) => l.length > 0 && !l.startsWith('@'))
357
- .join(' ')
358
- .trim() || undefined
359
- )
360
- }
361
- // Allow skipping over single-line comments before a JSDoc
362
- if (t.kind !== 'comment') break
363
- idx--
364
- }
365
- return undefined
366
- }
367
-
368
- // -- Top-level parsing -----------------------------------------------------
369
-
370
- private parse(): void {
371
- while (this.pos < this.tokens.length) {
372
- const t = this.peek()
373
- if (!t) break
374
-
375
- if (t.kind === 'word' && t.value === 'export') {
376
- const savedPos = this.pos
377
- this.advance()
378
- const next = this.peek()
379
- if (next?.kind === 'word' && next.value === 'type') {
380
- this.advance()
381
- try {
382
- this.parseTypeAlias()
383
- } catch {
384
- // Skip unparseable type alias — restore and skip to next export
385
- this.pos = savedPos + 1
386
- }
387
- continue
388
- }
389
- if (next?.kind === 'word' && next.value === 'interface') {
390
- this.advance()
391
- try {
392
- this.parseInterface()
393
- } catch {
394
- // Skip unparseable interface — restore and skip to next export
395
- this.pos = savedPos + 1
396
- }
397
- continue
398
- }
399
- }
400
-
401
- this.advance() // skip token
402
- }
403
- }
404
-
405
- private parseTypeAlias(): void {
406
- const nameTok = this.advance()
407
- if (!nameTok || nameTok.kind !== 'word') return
408
- const name = nameTok.value
409
- const description = this.collectJSDoc()
410
-
411
- // Handle generics: skip <T, ...>
412
- if (this.is('symbol', '<')) {
413
- this.skipBalanced('<', '>')
414
- }
415
-
416
- this.expect('symbol', '=')
417
- const expr = this.parseTypeExpr()
418
- this.defs.set(name, { name, expr, description })
419
- }
420
-
421
- private parseInterface(): void {
422
- const nameTok = this.advance()
423
- if (!nameTok || nameTok.kind !== 'word') return
424
- const name = nameTok.value
425
- const description = this.collectJSDoc()
426
-
427
- // Handle generics
428
- if (this.is('symbol', '<')) {
429
- this.skipBalanced('<', '>')
430
- }
431
-
432
- // Handle extends
433
- if (this.is('word', 'extends')) {
434
- this.advance()
435
- while (!this.is('symbol', '{')) this.advance()
436
- }
437
-
438
- const properties = this.parseObjectBody()
439
- this.defs.set(name, { name, expr: { kind: 'object', properties }, description })
440
- }
441
-
442
- // -- Type expression parsing -----------------------------------------------
443
-
444
- private parseTypeExpr(): TypeExpr {
445
- // Handle leading pipe: | 'a' | 'b' | 'c' (common in multi-line union types)
446
- if (this.is('symbol', '|')) {
447
- const members: TypeExpr[] = []
448
- while (this.matchMeaningful('symbol', '|')) {
449
- this.skipCommentsBeforeType()
450
- members.push(this.parsePrimaryType())
451
- }
452
- let expr: TypeExpr =
453
- members.length === 1 ? (members[0] as TypeExpr) : { kind: 'union', members }
454
- // Handle array suffix: T[]
455
- while (
456
- this.is('symbol', '[') &&
457
- this.peek(1)?.kind === 'symbol' &&
458
- this.peek(1)?.value === ']'
459
- ) {
460
- this.advance()
461
- this.advance()
462
- expr = { kind: 'array', element: expr }
463
- }
464
- return expr
465
- }
466
-
467
- let expr = this.parsePrimaryType()
468
-
469
- // Handle union: T | U | V — a member may carry its own JSDoc, so look past
470
- // comments for the `|`, but only consume them once one is actually found.
471
- if (this.isMeaningful('symbol', '|')) {
472
- const members: TypeExpr[] = [expr]
473
- while (this.matchMeaningful('symbol', '|')) {
474
- this.skipCommentsBeforeType()
475
- members.push(this.parsePrimaryType())
476
- }
477
- expr = { kind: 'union', members }
478
- }
479
-
480
- // Handle intersection: T & U (treat as first type for schema purposes)
481
- if (this.is('symbol', '&')) {
482
- while (this.match('symbol', '&')) {
483
- this.parsePrimaryType() // skip intersected types
484
- }
485
- }
486
-
487
- // Handle array suffix: T[]
488
- while (
489
- this.is('symbol', '[') &&
490
- this.peek(1)?.kind === 'symbol' &&
491
- this.peek(1)?.value === ']'
492
- ) {
493
- this.advance() // [
494
- this.advance() // ]
495
- expr = { kind: 'array', element: expr }
496
- }
497
-
498
- return expr
499
- }
500
-
501
- private parsePrimaryType(): TypeExpr {
502
- const t = this.peek()
503
- if (!t) return { kind: 'primitive', value: 'unknown' }
504
-
505
- // String literal
506
- if (t.kind === 'string') {
507
- this.advance()
508
- const val = t.value.slice(1, -1) // strip quotes
509
- return { kind: 'literal', value: val }
510
- }
511
-
512
- // Inline object type
513
- if (t.kind === 'symbol' && t.value === '{') {
514
- return this.parseInlineObject()
515
- }
516
-
517
- // Parenthesized type or function type: (args) => ReturnType
518
- if (t.kind === 'symbol' && t.value === '(') {
519
- // Peek ahead to detect function type: skip balanced parens then check for =>
520
- const savedPos = this.pos
521
- this.skipBalanced('(', ')')
522
- if (
523
- this.is('symbol', '=') &&
524
- this.peek(1)?.kind === 'symbol' &&
525
- this.peek(1)?.value === '>'
526
- ) {
527
- // Function type — skip return type and represent as unknown
528
- this.advance() // =
529
- this.advance() // >
530
- this.parseTypeExpr() // skip return type
531
- return { kind: 'primitive', value: 'unknown' }
532
- }
533
- // Not a function type — backtrack and parse as grouped type
534
- this.pos = savedPos
535
- this.advance() // (
536
- const inner = this.parseTypeExpr()
537
- this.expect('symbol', ')')
538
- // Handle array suffix after parens
539
- while (
540
- this.is('symbol', '[') &&
541
- this.peek(1)?.kind === 'symbol' &&
542
- this.peek(1)?.value === ']'
543
- ) {
544
- this.advance()
545
- this.advance()
546
- return { kind: 'array', element: inner }
547
- }
548
- return inner
549
- }
550
-
551
- // Array<T>
552
- if (t.kind === 'word' && t.value === 'Array') {
553
- this.advance()
554
- this.expect('symbol', '<')
555
- const element = this.parseTypeExpr()
556
- this.expect('symbol', '>')
557
- return { kind: 'array', element }
558
- }
559
-
560
- // Record<string, T>
561
- if (t.kind === 'word' && t.value === 'Record') {
562
- this.advance()
563
- this.expect('symbol', '<')
564
- this.parseTypeExpr() // key type (skip)
565
- this.expect('symbol', ',')
566
- const valueType = this.parseTypeExpr()
567
- this.expect('symbol', '>')
568
- return { kind: 'record', valueType }
569
- }
570
-
571
- // Partial<T>
572
- if (t.kind === 'word' && t.value === 'Partial') {
573
- this.advance()
574
- this.expect('symbol', '<')
575
- const inner = this.parseTypeExpr()
576
- this.expect('symbol', '>')
577
- return { kind: 'partial', inner }
578
- }
579
-
580
- // Primitives
581
- if (t.kind === 'word') {
582
- const val = t.value
583
- if (val === 'string' || val === 'number' || val === 'boolean') {
584
- this.advance()
585
- // Handle array suffix
586
- while (this.is('symbol', '[') && this.peek(1)?.value === ']') {
587
- this.advance()
588
- this.advance()
589
- return { kind: 'array', element: { kind: 'primitive', value: val } }
590
- }
591
- return { kind: 'primitive', value: val }
592
- }
593
- if (
594
- val === 'unknown' ||
595
- val === 'any' ||
596
- val === 'never' ||
597
- val === 'void' ||
598
- val === 'undefined' ||
599
- val === 'null'
600
- ) {
601
- this.advance()
602
- return { kind: 'primitive', value: 'unknown' }
603
- }
604
- // typeof operator — skip and treat as unknown
605
- if (val === 'typeof') {
606
- this.advance()
607
- // Skip the expression after typeof
608
- while (this.is('word') || this.is('symbol', '.') || this.is('symbol', '[')) {
609
- if (this.is('symbol', '[')) {
610
- this.skipBalanced('[', ']')
611
- } else {
612
- this.advance()
613
- }
614
- }
615
- return { kind: 'primitive', value: 'unknown' }
616
- }
617
- // keyof operator — skip and treat as string
618
- if (val === 'keyof') {
619
- this.advance()
620
- this.parsePrimaryType() // skip the type after keyof
621
- return { kind: 'primitive', value: 'string' }
622
- }
623
- // Named type reference
624
- this.advance()
625
- // Handle generics on reference: SomeType<T>
626
- if (this.is('symbol', '<')) {
627
- this.skipBalanced('<', '>')
628
- }
629
- // Handle array suffix
630
- while (this.is('symbol', '[') && this.peek(1)?.value === ']') {
631
- this.advance()
632
- this.advance()
633
- return { kind: 'array', element: { kind: 'reference', name: val } }
634
- }
635
- return { kind: 'reference', name: val }
636
- }
637
-
638
- // Number literal (skip)
639
- if (t.kind === 'number') {
640
- this.advance()
641
- return { kind: 'primitive', value: 'number' }
642
- }
643
-
644
- this.advance()
645
- return { kind: 'primitive', value: 'unknown' }
646
- }
647
-
648
- private parseInlineObject(): TypeExpr {
649
- const properties = this.parseObjectBody()
650
- return { kind: 'object', properties }
651
- }
652
-
653
- private parseObjectBody(): ParsedProperty[] {
654
- this.expect('symbol', '{')
655
- const properties: ParsedProperty[] = []
656
-
657
- while (!this.is('symbol', '}') && this.pos < this.tokens.length) {
658
- // Collect JSDoc/comments above property
659
- let description: string | undefined
660
- while (this.peek()?.kind === 'comment' || this.peek()?.kind === 'multiline_comment') {
661
- const commentTok = this.advance()
662
- if (commentTok.kind === 'multiline_comment' && commentTok.value.startsWith('/**')) {
663
- description =
664
- commentTok.value
665
- .replace(/^\/\*\*\s*/, '')
666
- .replace(/\s*\*\/$/, '')
667
- .split('\n')
668
- .map((l) => l.replace(/^\s*\*\s?/, '').trim())
669
- .filter((l) => l.length > 0 && !l.startsWith('@'))
670
- .join(' ')
671
- .trim() || undefined
672
- } else if (commentTok.kind === 'comment') {
673
- const text = commentTok.value.replace(/^\/\/\s*/, '').trim()
674
- if (text) description = text
675
- }
676
- }
677
-
678
- // Skip semicolons
679
- if (this.is('symbol', ';')) {
680
- this.advance()
681
- continue
682
- }
683
-
684
- // End of object
685
- if (this.is('symbol', '}')) break
686
-
687
- // Index signature: [key: string]: ValueType
688
- if (this.is('symbol', '[')) {
689
- this.skipBalanced('[', ']')
690
- this.expect('symbol', ':')
691
- this.parseTypeExpr() // skip index signature value type
692
- this.match('symbol', ';')
693
- continue
694
- }
695
-
696
- // Property name
697
- const nameTok = this.peek()
698
- if (!nameTok || nameTok.kind !== 'word') {
699
- this.advance()
700
- continue
701
- }
702
- this.advance()
703
- const propName = nameTok.value
704
-
705
- // Optional marker
706
- const optional = this.match('symbol', '?')
707
-
708
- // Colon
709
- if (!this.match('symbol', ':')) {
710
- // Could be a method signature — skip to semicolon or closing brace
711
- while (
712
- !this.is('symbol', ';') &&
713
- !this.is('symbol', '}') &&
714
- this.pos < this.tokens.length
715
- ) {
716
- this.advance()
717
- }
718
- this.match('symbol', ';')
719
- continue
720
- }
721
-
722
- const typeExpr = this.parseTypeExpr()
723
-
724
- // Skip trailing semicolon/comma
725
- this.match('symbol', ';')
726
- this.match('symbol', ',')
727
-
728
- properties.push({ name: propName, optional, typeExpr, description })
729
- }
730
-
731
- this.expect('symbol', '}')
732
- return properties
733
- }
734
-
735
- private skipBalanced(open: string, close: string): void {
736
- this.expect('symbol', open)
737
- let depth = 1
738
- while (depth > 0 && this.pos < this.tokens.length) {
739
- const t = this.advance()
740
- if (t.kind === 'symbol' && t.value === open) depth++
741
- if (t.kind === 'symbol' && t.value === close) depth--
742
- }
743
- }
744
- }
745
-
746
- // ---------------------------------------------------------------------------
747
- // TypeExpr → JSON Schema conversion (recursive, with reference resolution)
748
- // ---------------------------------------------------------------------------
749
- class SchemaGenerator {
750
- private parser: TypeParser
751
- private resolving: Set<string> = new Set() // cycle guard
752
-
753
- constructor(parser: TypeParser) {
754
- this.parser = parser
755
- }
756
-
757
- typeExprToSchema(expr: TypeExpr): SchemaNode {
758
- switch (expr.kind) {
759
- case 'primitive':
760
- if (expr.value === 'unknown' || expr.value === 'any') return {}
761
- return { type: expr.value }
762
-
763
- case 'literal':
764
- return { type: 'string', enum: [expr.value] }
765
-
766
- case 'union':
767
- return this.unionToSchema(expr.members)
768
-
769
- case 'array':
770
- return { type: 'array', items: this.typeExprToSchema(expr.element) }
771
-
772
- case 'object':
773
- return this.objectToSchema(expr.properties)
774
-
775
- case 'record':
776
- return { type: 'object', additionalProperties: this.typeExprToSchema(expr.valueType) }
777
-
778
- case 'partial': {
779
- const inner = this.typeExprToSchema(expr.inner)
780
- // Partial makes all required fields optional
781
- const result = { ...inner }
782
- // biome-ignore lint/performance/noDelete: must remove the JSON-schema key entirely (undefined would still serialize the property)
783
- delete result.required
784
- return result
785
- }
786
-
787
- case 'reference':
788
- return this.resolveReference(expr.name)
789
-
790
- case 'tuple':
791
- return {
792
- type: 'array',
793
- items: this.typeExprToSchema(expr.elements[0] ?? { kind: 'primitive', value: 'unknown' }),
794
- }
795
- }
796
- }
797
-
798
- private unionToSchema(members: TypeExpr[]): SchemaNode {
799
- // Filter out null/undefined
800
- const filtered = members.filter((m) => !(m.kind === 'primitive' && m.value === 'unknown'))
801
- if (filtered.length === 0) return {}
802
- if (filtered.length === 1) return this.typeExprToSchema(filtered[0] as TypeExpr)
803
-
804
- // Check if all members are string literals → enum
805
- const allLiterals = filtered.every((m) => m.kind === 'literal')
806
- if (allLiterals) {
807
- const values = filtered.map((m) => (m as { kind: 'literal'; value: string }).value)
808
- return { type: 'string', enum: values }
809
- }
810
-
811
- // Check if all members are the same primitive
812
- const allSamePrimitive = filtered.every(
813
- (m) =>
814
- m.kind === 'primitive' &&
815
- m.value === (filtered[0] as { kind: 'primitive'; value: string }).value
816
- )
817
- if (allSamePrimitive && filtered[0]?.kind === 'primitive') {
818
- return { type: filtered[0].value }
819
- }
820
-
821
- // Mixed union — use anyOf
822
- const schemas = filtered.map((m) => this.typeExprToSchema(m))
823
- // Deduplicate simple schemas
824
- const unique = this.deduplicateSchemas(schemas)
825
- if (unique.length === 1) return unique[0] as SchemaNode
826
- return { anyOf: unique }
827
- }
828
-
829
- private deduplicateSchemas(schemas: SchemaNode[]): SchemaNode[] {
830
- const seen = new Set<string>()
831
- const result: SchemaNode[] = []
832
- for (const s of schemas) {
833
- const key = JSON.stringify(s)
834
- if (!seen.has(key)) {
835
- seen.add(key)
836
- result.push(s)
837
- }
838
- }
839
- return result
840
- }
841
-
842
- private objectToSchema(properties: ParsedProperty[]): SchemaNode {
843
- const props: Record<string, SchemaNode> = {}
844
- const required: string[] = []
845
-
846
- for (const prop of properties) {
847
- const schema = this.typeExprToSchema(prop.typeExpr)
848
- if (prop.description) {
849
- schema.description = prop.description
850
- }
851
- props[prop.name] = schema
852
- if (!prop.optional) {
853
- required.push(prop.name)
854
- }
855
- }
856
-
857
- const result: SchemaNode = { type: 'object', properties: props }
858
- if (required.length > 0) {
859
- result.required = required
860
- }
861
- return result
862
- }
863
-
864
- resolveReference(name: string): SchemaNode {
865
- // Cycle guard
866
- if (this.resolving.has(name)) {
867
- return { type: 'object' }
868
- }
869
- this.resolving.add(name)
870
-
871
- const def = this.parser.getDefinition(name)
872
- if (!def) {
873
- this.resolving.delete(name)
874
- // Fallback: could be an external type we don't know about
875
- return { type: 'string' }
876
- }
877
-
878
- const result = this.typeExprToSchema(def.expr)
879
- if (def.description && !result.description) {
880
- result.description = def.description
881
- }
882
- this.resolving.delete(name)
883
- return result
884
- }
885
- }
886
-
887
- // ---------------------------------------------------------------------------
888
- // Schema generators for each output file
889
- // ---------------------------------------------------------------------------
890
-
891
- function generateNucleusTableSchema(gen: SchemaGenerator, parser: TypeParser): JsonSchema {
892
- const tableDef = parser.getDefinition('NucleusTable')
893
- if (!tableDef) throw new Error('NucleusTable not found in types.ts')
894
-
895
- const tableSchema = gen.typeExprToSchema(tableDef.expr) as JsonSchema
896
-
897
- // Collect $defs from sub-interfaces that are referenced by NucleusTable
898
- const defs: Record<string, SchemaNode> = {}
899
- const subTypes = [
900
- 'NucleusColumn',
901
- 'NucleusIndex',
902
- 'NucleusConstraints',
903
- 'NucleusUniqueConstraint',
904
- 'NucleusCheckConstraint',
905
- 'NucleusColumnReference',
906
- 'NucleusColumnEnum',
907
- 'NucleusColumnValidation',
908
- ]
909
-
910
- const defNameMap: Record<string, string> = {
911
- NucleusColumn: 'column',
912
- NucleusIndex: 'index',
913
- NucleusConstraints: 'constraints',
914
- NucleusUniqueConstraint: 'uniqueConstraint',
915
- NucleusCheckConstraint: 'checkConstraint',
916
- NucleusColumnReference: 'columnReference',
917
- NucleusColumnEnum: 'columnEnum',
918
- NucleusColumnValidation: 'columnValidation',
919
- }
920
-
921
- for (const typeName of subTypes) {
922
- const def = parser.getDefinition(typeName)
923
- if (def) {
924
- const shortName = defNameMap[typeName] ?? typeName
925
- defs[shortName] = gen.typeExprToSchema(def.expr)
926
- }
927
- }
928
-
929
- // Replace inline expansions of known sub-types with $ref
930
- if (tableSchema.properties) {
931
- replaceWithRefs(tableSchema.properties, defs, defNameMap)
932
- }
933
-
934
- return {
935
- $id: 'table.schema.json',
936
- $schema: 'https://json-schema.org/draft/2020-12/schema',
937
- title: 'Nucleus Table Definition',
938
- description: 'Generated from NucleusTable interface in types.ts',
939
- type: 'object',
940
- properties: {
941
- ...tableSchema.properties,
942
- },
943
- required: tableSchema.required ?? ['table_name'],
944
- additionalProperties: false,
945
- $defs: defs,
946
- }
947
- }
948
-
949
- function replaceWithRefs(
950
- props: Record<string, SchemaNode>,
951
- defs: Record<string, SchemaNode>,
952
- nameMap: Record<string, string>
953
- ): void {
954
- const reverseMap: Record<string, string> = {}
955
- for (const [full, short] of Object.entries(nameMap)) {
956
- reverseMap[full] = short
957
- }
958
-
959
- for (const [key, schema] of Object.entries(props)) {
960
- // If this property's schema matches a known $def, replace with $ref
961
- for (const [, shortName] of Object.entries(nameMap)) {
962
- if (shortName && defs[shortName]) {
963
- const defStr = JSON.stringify(defs[shortName])
964
- const schemaStr = JSON.stringify(schema)
965
- if (schemaStr === defStr) {
966
- props[key] = { $ref: `#/$defs/${shortName}` }
967
- break
968
- }
969
- // Check if it's an array of this type
970
- if (schema.type === 'array' && schema.items) {
971
- const itemsStr = JSON.stringify(schema.items)
972
- if (itemsStr === defStr) {
973
- schema.items = { $ref: `#/$defs/${shortName}` }
974
- }
975
- }
976
- }
977
- }
978
- }
979
- }
980
-
981
- // ---------------------------------------------------------------------------
982
- // Auto-deduplication: detect repeated object schemas and extract into $defs
983
- // ---------------------------------------------------------------------------
984
-
985
- type SchemaPath = { obj: Record<string, SchemaNode>; key: string; fullPath: string }
986
-
987
- function collectObjectSchemas(
988
- node: SchemaNode,
989
- parentObj: Record<string, SchemaNode> | null,
990
- parentKey: string | null,
991
- pathPrefix: string,
992
- results: Map<string, { hash: string; path: string; locations: SchemaPath[] }>
993
- ): void {
994
- if (!node || typeof node !== 'object') return
995
-
996
- // Only deduplicate object schemas with 3+ properties (worth extracting)
997
- if (node.type === 'object' && node.properties && Object.keys(node.properties).length >= 3) {
998
- // Create a canonical hash (without description to match structurally identical schemas)
999
- const canonical = { ...node }
1000
- // biome-ignore lint/performance/noDelete: must drop the key for structural hashing (undefined would still appear in the canonical shape)
1001
- delete canonical.description
1002
- const hash = JSON.stringify(canonical)
1003
-
1004
- const existing = results.get(hash)
1005
- if (!existing) {
1006
- results.set(hash, { hash, path: pathPrefix, locations: [] })
1007
- }
1008
- if (parentObj && parentKey) {
1009
- ;(results.get(hash) as { locations: SchemaPath[] }).locations.push({
1010
- obj: parentObj,
1011
- key: parentKey,
1012
- fullPath: pathPrefix,
1013
- })
1014
- }
1015
- }
1016
-
1017
- // Recurse into properties
1018
- if (node.properties) {
1019
- for (const [key, child] of Object.entries(node.properties)) {
1020
- collectObjectSchemas(child, node.properties, key, `${pathPrefix}.${key}`, results)
1021
- }
1022
- }
1023
-
1024
- // Recurse into array items
1025
- if (node.type === 'array' && node.items && typeof node.items === 'object') {
1026
- collectObjectSchemas(node.items, null, null, `${pathPrefix}[]`, results)
1027
- if (node.items.properties) {
1028
- for (const [key, child] of Object.entries(node.items.properties)) {
1029
- collectObjectSchemas(child, node.items.properties, key, `${pathPrefix}[].${key}`, results)
1030
- }
1031
- }
1032
- }
1033
-
1034
- // Recurse into anyOf
1035
- if (node.anyOf) {
1036
- for (let i = 0; i < node.anyOf.length; i++) {
1037
- collectObjectSchemas(
1038
- node.anyOf[i] as SchemaNode,
1039
- null,
1040
- null,
1041
- `${pathPrefix}.anyOf[${i}]`,
1042
- results
1043
- )
1044
- }
1045
- }
1046
- }
1047
-
1048
- function deriveDefName(locations: SchemaPath[], schema: SchemaNode): string {
1049
- const keys = locations.map((l) => l.key)
1050
- const fullPaths = locations.map((l) => l.fullPath)
1051
- const propKeys = schema.properties ? Object.keys(schema.properties) : []
1052
-
1053
- // ---- Heuristic 1: name by schema content shape ----
1054
- // Token configs: secret + expiresIn + algorithm
1055
- if (
1056
- propKeys.includes('secret') &&
1057
- propKeys.includes('expiresIn') &&
1058
- propKeys.includes('algorithm')
1059
- ) {
1060
- return 'tokenConfig'
1061
- }
1062
- // OAuth provider: clientId + clientSecret + redirectUri
1063
- if (
1064
- propKeys.includes('clientId') &&
1065
- propKeys.includes('clientSecret') &&
1066
- propKeys.includes('redirectUri')
1067
- ) {
1068
- return 'oauthProvider'
1069
- }
1070
- // Rate limit rule: window + max
1071
- if (propKeys.includes('window') && propKeys.includes('max')) {
1072
- if (propKeys.includes('blockDuration')) return 'rateLimitRule'
1073
- return 'rateLimitWindow'
1074
- }
1075
- // Endpoint config: enabled + basePath
1076
- if (propKeys.length <= 3 && propKeys.includes('enabled') && propKeys.includes('basePath')) {
1077
- return 'endpointConfig'
1078
- }
1079
-
1080
- // ---- Heuristic 2: content-based — route + isPublic + enabled pattern ----
1081
- if (propKeys.includes('route') && propKeys.includes('isPublic') && propKeys.includes('enabled')) {
1082
- return 'authRoute'
1083
- }
1084
-
1085
- // ---- Heuristic 3: common parent context ----
1086
- // All under the same parent (e.g. authentication.providers.*) → use parent segment
1087
- const parents = fullPaths.map((p) => {
1088
- const parts = p.split('.')
1089
- parts.pop()
1090
- return parts.pop() ?? ''
1091
- })
1092
- const allSameParent = parents.every((p) => p === parents[0])
1093
- if (allSameParent && parents[0]) {
1094
- const parent = parents[0]
1095
- return parent.endsWith('s') ? parent.slice(0, -1) : parent
1096
- }
1097
-
1098
- // ---- Heuristic 4: common suffix ----
1099
- const commonSuffix = findCommonSuffix(keys)
1100
- if (commonSuffix && commonSuffix.length > 2) {
1101
- return `${commonSuffix.charAt(0).toLowerCase() + commonSuffix.slice(1)}Config`
1102
- }
1103
-
1104
- // Fallback: first key
1105
- return keys[0] ?? 'unnamed'
1106
- }
1107
-
1108
- function deduplicateConfigSchema(schema: JsonSchema): Record<string, SchemaNode> {
1109
- const defs: Record<string, SchemaNode> = {}
1110
- if (!schema.properties) return defs
1111
-
1112
- const schemaMap = new Map<string, { hash: string; path: string; locations: SchemaPath[] }>()
1113
-
1114
- // Collect all object schemas with their locations
1115
- for (const [key, child] of Object.entries(schema.properties)) {
1116
- collectObjectSchemas(child, schema.properties, key, key, schemaMap)
1117
- }
1118
-
1119
- // Find duplicates (2+ occurrences) and extract into $defs
1120
- const usedNames = new Set<string>()
1121
-
1122
- for (const [hash, entry] of schemaMap.entries()) {
1123
- if (entry.locations.length < 2) continue
1124
-
1125
- const defSchema = JSON.parse(hash) as SchemaNode
1126
- const baseName = deriveDefName(entry.locations, defSchema)
1127
-
1128
- // Ensure unique name
1129
- let defName = baseName
1130
- let counter = 1
1131
- while (usedNames.has(defName)) {
1132
- defName = `${baseName}${counter++}`
1133
- }
1134
- usedNames.add(defName)
1135
-
1136
- defs[defName] = defSchema
1137
-
1138
- // Replace all occurrences with $ref
1139
- for (const loc of entry.locations) {
1140
- const original = loc.obj[loc.key]
1141
- const ref: SchemaNode = { $ref: `#/$defs/${defName}` }
1142
- if (original?.description) {
1143
- ref.description = original.description
1144
- }
1145
- loc.obj[loc.key] = ref
1146
- }
1147
- }
1148
-
1149
- return defs
1150
- }
1151
-
1152
- function findCommonSuffix(words: string[]): string {
1153
- if (words.length === 0) return ''
1154
- const splitCamel = (s: string) => s.replace(/([a-z])([A-Z])/g, '$1 $2').split(' ')
1155
- const parts = words.map(splitCamel)
1156
- const minLen = Math.min(...parts.map((p) => p.length))
1157
-
1158
- const common: string[] = []
1159
- for (let i = 1; i <= minLen; i++) {
1160
- const suffix = parts[0]?.[parts[0].length - i]?.toLowerCase()
1161
- if (suffix && parts.every((p) => p[p.length - i]?.toLowerCase() === suffix)) {
1162
- common.unshift(suffix)
1163
- } else {
1164
- break
1165
- }
1166
- }
1167
-
1168
- return common.map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join('')
1169
- }
1170
-
1171
- function generateNucleusConfigSchema(gen: SchemaGenerator, parser: TypeParser): JsonSchema {
1172
- const configDef = parser.getDefinition('NucleusConfigOptions')
1173
- if (!configDef) throw new Error('NucleusConfigOptions not found in types.ts')
1174
-
1175
- const configSchema = gen.typeExprToSchema(configDef.expr) as JsonSchema
1176
-
1177
- // Add $schema property for config files
1178
- if (configSchema.properties) {
1179
- configSchema.properties = {
1180
- $schema: { type: 'string', description: 'JSON Schema reference' },
1181
- ...configSchema.properties,
1182
- }
1183
- }
1184
-
1185
- // The entities field should reference table.schema.json
1186
- if (configSchema.properties?.entities) {
1187
- configSchema.properties.entities = {
1188
- type: 'array',
1189
- description: 'Entity/table definitions',
1190
- items: { $ref: 'table.schema.json' },
1191
- }
1192
- }
1193
-
1194
- // externalEntities in authorization should also reference table.schema.json
1195
- if (configSchema.properties?.authorization?.properties?.externalEntities) {
1196
- configSchema.properties.authorization.properties.externalEntities = {
1197
- type: 'array',
1198
- description: 'Entity definitions from external consumer services',
1199
- items: { $ref: 'table.schema.json' },
1200
- }
1201
- }
1202
-
1203
- // Auto-deduplicate repeated inline schemas into $defs
1204
- const defs = deduplicateConfigSchema(configSchema)
1205
-
1206
- const result: JsonSchema = {
1207
- $id: 'config.nucleus.json',
1208
- $schema: 'https://json-schema.org/draft/2020-12/schema',
1209
- title: 'Nucleus Config',
1210
- description: 'Generated from NucleusConfigOptions interface in types.ts',
1211
- type: 'object',
1212
- properties: configSchema.properties,
1213
- required: configSchema.required ?? ['appId', 'entities'],
1214
- additionalProperties: false,
1215
- }
1216
-
1217
- if (Object.keys(defs).length > 0) {
1218
- result.$defs = defs
1219
- console.log(` Extracted ${Object.keys(defs).length} $defs: ${Object.keys(defs).join(', ')}`)
1220
- }
1221
-
1222
- return result
1223
- }
1224
-
1225
- function generateTablesArraySchema(): JsonSchema {
1226
- return {
1227
- $id: 'nucleus.tables.schema.json',
1228
- $schema: 'https://json-schema.org/draft/2020-12/schema',
1229
- title: 'Nucleus Tables Array',
1230
- description: 'Array of Nucleus table definitions',
1231
- type: 'object',
1232
- properties: {
1233
- $schema: { type: 'string' },
1234
- tables: {
1235
- type: 'array',
1236
- items: { $ref: 'table.schema.json' },
1237
- },
1238
- },
1239
- required: ['tables'],
1240
- }
1241
- }
1242
-
1243
- // ---------------------------------------------------------------------------
1244
- // Main
1245
- // ---------------------------------------------------------------------------
1246
- function main() {
1247
- console.log('Reading types.ts and imported files...')
1248
- const sources = loadSources()
1249
- console.log(` Loaded ${sources.length} source file(s)`)
1250
-
1251
- console.log('Parsing type definitions...')
1252
- const parser = new TypeParser(sources)
1253
- console.log(` Found ${parser.getAllDefs().size} type definitions`)
1254
-
1255
- const gen = new SchemaGenerator(parser)
1256
-
1257
- console.log('Generating table.schema.json...')
1258
- const tableSchema = generateNucleusTableSchema(gen, parser)
1259
- fs.writeFileSync(
1260
- path.join(SCHEMAS_DIR, 'table.schema.json'),
1261
- `${JSON.stringify(tableSchema, null, 2)}\n`
1262
- )
1263
-
1264
- console.log('Generating config.nucleus.json...')
1265
- const configSchema = generateNucleusConfigSchema(gen, parser)
1266
- fs.writeFileSync(
1267
- path.join(SCHEMAS_DIR, 'config.nucleus.json'),
1268
- `${JSON.stringify(configSchema, null, 2)}\n`
1269
- )
1270
-
1271
- console.log('Generating nucleus.tables.schema.json...')
1272
- const tablesSchema = generateTablesArraySchema()
1273
- fs.writeFileSync(
1274
- path.join(SCHEMAS_DIR, 'nucleus.tables.schema.json'),
1275
- `${JSON.stringify(tablesSchema, null, 2)}\n`
1276
- )
1277
-
1278
- console.log('Schemas generated successfully!')
1279
- console.log(` - ${SCHEMAS_DIR}/table.schema.json`)
1280
- console.log(` - ${SCHEMAS_DIR}/config.nucleus.json`)
1281
- console.log(` - ${SCHEMAS_DIR}/nucleus.tables.schema.json`)
1282
- }
1283
-
1284
- main()
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * Fully automated JSON Schema generator from TypeScript types in src/types.ts.
4
+ * Recursively parses type aliases, interfaces, inline object types, unions,
5
+ * arrays, Record<K,V>, Partial<T>, and imported type references.
6
+ *
7
+ * Run: bun run scripts/generate-types-schema.ts
8
+ */
9
+
10
+ import * as fs from 'node:fs'
11
+ import * as path from 'node:path'
12
+
13
+ const TYPES_FILE = path.resolve(import.meta.dir, '../src/types.ts')
14
+ const SCHEMAS_DIR = path.resolve(import.meta.dir, '../schemas')
15
+
16
+ // ---------------------------------------------------------------------------
17
+ // Schema types
18
+ // ---------------------------------------------------------------------------
19
+ type SchemaNode = {
20
+ type?: string | string[]
21
+ description?: string
22
+ enum?: string[]
23
+ items?: SchemaNode
24
+ properties?: Record<string, SchemaNode>
25
+ required?: string[]
26
+ default?: unknown
27
+ $ref?: string
28
+ additionalProperties?: boolean | SchemaNode
29
+ minLength?: number
30
+ maxLength?: number
31
+ minimum?: number
32
+ maximum?: number
33
+ oneOf?: SchemaNode[]
34
+ anyOf?: SchemaNode[]
35
+ }
36
+
37
+ type JsonSchema = {
38
+ $id?: string
39
+ $schema?: string
40
+ title?: string
41
+ description?: string
42
+ type?: string
43
+ properties?: Record<string, SchemaNode>
44
+ required?: string[]
45
+ $defs?: Record<string, SchemaNode>
46
+ additionalProperties?: boolean
47
+ }
48
+
49
+ // ---------------------------------------------------------------------------
50
+ // Source loader – loads types.ts + resolves imported type files
51
+ // ---------------------------------------------------------------------------
52
+ type SourceFile = { path: string; content: string }
53
+
54
+ const PROJECT_ROOT = path.resolve(import.meta.dir, '..')
55
+
56
+ function resolveModulePath(fromFile: string, modulePath: string): string | null {
57
+ // Try relative resolution first
58
+ const relCandidates = [
59
+ path.resolve(path.dirname(fromFile), `${modulePath}.ts`),
60
+ path.resolve(path.dirname(fromFile), modulePath, 'index.ts'),
61
+ path.resolve(path.dirname(fromFile), modulePath, 'types.ts'),
62
+ ]
63
+ for (const c of relCandidates) {
64
+ if (fs.existsSync(c)) return c
65
+ }
66
+
67
+ // Try tsconfig baseUrl resolution (baseUrl: ".")
68
+ const baseCandidates = [
69
+ path.resolve(PROJECT_ROOT, `${modulePath}.ts`),
70
+ path.resolve(PROJECT_ROOT, modulePath, 'index.ts'),
71
+ path.resolve(PROJECT_ROOT, modulePath, 'types.ts'),
72
+ ]
73
+ for (const c of baseCandidates) {
74
+ if (fs.existsSync(c)) return c
75
+ }
76
+
77
+ return null
78
+ }
79
+
80
+ function collectExportedFiles(filePath: string, visited: Set<string>): SourceFile[] {
81
+ if (visited.has(filePath)) return []
82
+ visited.add(filePath)
83
+
84
+ const content = fs.readFileSync(filePath, 'utf-8')
85
+ const results: SourceFile[] = [{ path: filePath, content }]
86
+
87
+ // Follow `export * from './...'` re-exports
88
+ const reExportRegex = /export\s+\*\s+from\s+['"]([^'"]+)['"]/g
89
+ let rem: RegExpExecArray | null = reExportRegex.exec(content)
90
+ while (rem !== null) {
91
+ const reExportPath = rem[1]
92
+ if (reExportPath) {
93
+ const resolved = resolveModulePath(filePath, reExportPath)
94
+ if (resolved) {
95
+ results.push(...collectExportedFiles(resolved, visited))
96
+ }
97
+ }
98
+ rem = reExportRegex.exec(content)
99
+ }
100
+
101
+ return results
102
+ }
103
+
104
+ function loadSources(): SourceFile[] {
105
+ const main = fs.readFileSync(TYPES_FILE, 'utf-8')
106
+ const visited = new Set<string>([TYPES_FILE])
107
+ const sources: SourceFile[] = [{ path: TYPES_FILE, content: main }]
108
+
109
+ // Resolve imports from the main types file
110
+ const importRegex = /import\s+(?:type\s+)?{([^}]+)}\s+from\s+['"]([^'"]+)['"]/g
111
+ let m: RegExpExecArray | null = importRegex.exec(main)
112
+ while (m !== null) {
113
+ const modulePath = m[2]
114
+ if (!modulePath || modulePath.startsWith('node:')) {
115
+ m = importRegex.exec(main)
116
+ continue
117
+ }
118
+ const resolved = resolveModulePath(TYPES_FILE, modulePath)
119
+ if (resolved) {
120
+ sources.push(...collectExportedFiles(resolved, visited))
121
+ }
122
+ m = importRegex.exec(main)
123
+ }
124
+
125
+ return sources
126
+ }
127
+
128
+ // ---------------------------------------------------------------------------
129
+ // Tokenizer – splits TS source into a stream of meaningful tokens
130
+ // ---------------------------------------------------------------------------
131
+ type Token = {
132
+ kind: 'word' | 'string' | 'number' | 'symbol' | 'comment' | 'multiline_comment'
133
+ value: string
134
+ pos: number
135
+ }
136
+
137
+ function tokenize(source: string): Token[] {
138
+ const tokens: Token[] = []
139
+ let i = 0
140
+ const len = source.length
141
+
142
+ while (i < len) {
143
+ // Skip whitespace
144
+ if (/\s/.test(source[i] as string)) {
145
+ i++
146
+ continue
147
+ }
148
+
149
+ // Single-line comment
150
+ if (source[i] === '/' && source[i + 1] === '/') {
151
+ const start = i
152
+ while (i < len && source[i] !== '\n') i++
153
+ tokens.push({ kind: 'comment', value: source.slice(start, i), pos: start })
154
+ continue
155
+ }
156
+
157
+ // Multi-line comment / JSDoc
158
+ if (source[i] === '/' && source[i + 1] === '*') {
159
+ const start = i
160
+ i += 2
161
+ while (i < len - 1 && !(source[i] === '*' && source[i + 1] === '/')) i++
162
+ i += 2
163
+ tokens.push({ kind: 'multiline_comment', value: source.slice(start, i), pos: start })
164
+ continue
165
+ }
166
+
167
+ // String literal
168
+ if (source[i] === "'" || source[i] === '"' || source[i] === '`') {
169
+ const quote = source[i]
170
+ const start = i
171
+ i++
172
+ while (i < len && source[i] !== quote) {
173
+ if (source[i] === '\\') i++
174
+ i++
175
+ }
176
+ i++ // closing quote
177
+ tokens.push({ kind: 'string', value: source.slice(start, i), pos: start })
178
+ continue
179
+ }
180
+
181
+ // Number
182
+ if (/[0-9]/.test(source[i] as string)) {
183
+ const start = i
184
+ while (i < len && /[0-9.]/.test(source[i] as string)) i++
185
+ tokens.push({ kind: 'number', value: source.slice(start, i), pos: start })
186
+ continue
187
+ }
188
+
189
+ // Word (identifier / keyword)
190
+ if (/[a-zA-Z_$]/.test(source[i] as string)) {
191
+ const start = i
192
+ while (i < len && /[a-zA-Z0-9_$]/.test(source[i] as string)) i++
193
+ tokens.push({ kind: 'word', value: source.slice(start, i), pos: start })
194
+ continue
195
+ }
196
+
197
+ // Symbols
198
+ tokens.push({ kind: 'symbol', value: source[i] as string, pos: i })
199
+ i++
200
+ }
201
+
202
+ return tokens
203
+ }
204
+
205
+ // ---------------------------------------------------------------------------
206
+ // Type registry – collects all exported types / interfaces from all sources
207
+ // ---------------------------------------------------------------------------
208
+ type ParsedProperty = {
209
+ name: string
210
+ optional: boolean
211
+ typeExpr: TypeExpr
212
+ description?: string
213
+ }
214
+
215
+ type TypeExpr =
216
+ | { kind: 'primitive'; value: 'string' | 'number' | 'boolean' | 'unknown' | 'any' }
217
+ | { kind: 'literal'; value: string } // e.g. 'HS256'
218
+ | { kind: 'union'; members: TypeExpr[] }
219
+ | { kind: 'array'; element: TypeExpr }
220
+ | { kind: 'object'; properties: ParsedProperty[]; indexSignature?: TypeExpr }
221
+ | { kind: 'record'; valueType: TypeExpr }
222
+ | { kind: 'partial'; inner: TypeExpr }
223
+ | { kind: 'reference'; name: string }
224
+ | { kind: 'tuple'; elements: TypeExpr[] }
225
+
226
+ type TypeDef = {
227
+ name: string
228
+ expr: TypeExpr
229
+ description?: string
230
+ }
231
+
232
+ // ---------------------------------------------------------------------------
233
+ // Token-stream parser
234
+ // ---------------------------------------------------------------------------
235
+ class TypeParser {
236
+ private tokens: Token[]
237
+ private pos: number
238
+ private defs: Map<string, TypeDef> = new Map()
239
+
240
+ constructor(sources: SourceFile[]) {
241
+ this.tokens = []
242
+ this.pos = 0
243
+ for (const src of sources) {
244
+ this.tokens.push(...tokenize(src.content))
245
+ }
246
+ this.parse()
247
+ }
248
+
249
+ getDefinition(name: string): TypeDef | undefined {
250
+ return this.defs.get(name)
251
+ }
252
+
253
+ getAllDefs(): Map<string, TypeDef> {
254
+ return this.defs
255
+ }
256
+
257
+ // -- Helpers ---------------------------------------------------------------
258
+
259
+ private peek(offset = 0): Token | undefined {
260
+ return this.tokens[this.pos + offset]
261
+ }
262
+
263
+ private advance(): Token {
264
+ const t = this.tokens[this.pos]
265
+ this.pos++
266
+ return t as Token
267
+ }
268
+
269
+ private expect(kind: Token['kind'], value?: string): Token {
270
+ const t = this.advance()
271
+ if (!t || t.kind !== kind || (value !== undefined && t.value !== value)) {
272
+ throw new Error(
273
+ `Expected ${kind}${value ? ` '${value}'` : ''} at pos ${this.pos - 1}, got ${t?.kind} '${t?.value}'`
274
+ )
275
+ }
276
+ return t
277
+ }
278
+
279
+ private match(kind: Token['kind'], value?: string): boolean {
280
+ const t = this.peek()
281
+ if (t && t.kind === kind && (value === undefined || t.value === value)) {
282
+ this.advance()
283
+ return true
284
+ }
285
+ return false
286
+ }
287
+
288
+ private is(kind: Token['kind'], value?: string): boolean {
289
+ const t = this.peek()
290
+ return !!t && t.kind === kind && (value === undefined || t.value === value)
291
+ }
292
+
293
+ /**
294
+ * Index of the next token that is not a comment, starting at `from`.
295
+ *
296
+ * Comments are kept in the token stream because property descriptions are read
297
+ * out of it, so the type-expression parser has to step over them explicitly.
298
+ */
299
+ private nextMeaningful(from: number): number {
300
+ let i = from
301
+ while (
302
+ this.tokens[i] &&
303
+ (this.tokens[i]?.kind === 'comment' || this.tokens[i]?.kind === 'multiline_comment')
304
+ ) {
305
+ i++
306
+ }
307
+ return i
308
+ }
309
+
310
+ /** Like `is`, but tolerates comments sitting in front of the token. */
311
+ private isMeaningful(kind: Token['kind'], value?: string): boolean {
312
+ const t = this.tokens[this.nextMeaningful(this.pos)]
313
+ return !!t && t.kind === kind && (value === undefined || t.value === value)
314
+ }
315
+
316
+ /**
317
+ * Like `match`, but tolerates comments in front of the token — and only consumes
318
+ * them when the token actually matches.
319
+ *
320
+ * That conditional consumption is the whole point. A union member may carry its
321
+ * own JSDoc (`| string[] /** … *\/ | string`), and without stepping over it the
322
+ * parser saw a comment where it expected `|`, ended the union early and desynced
323
+ * for the rest of the file — silently dropping every later property. Consuming
324
+ * comments UNCONDITIONALLY would be just as wrong the other way: the comment
325
+ * after a non-union property belongs to the NEXT property and is its description.
326
+ */
327
+ private matchMeaningful(kind: Token['kind'], value?: string): boolean {
328
+ const i = this.nextMeaningful(this.pos)
329
+ const t = this.tokens[i]
330
+ if (t && t.kind === kind && (value === undefined || t.value === value)) {
331
+ this.pos = i + 1
332
+ return true
333
+ }
334
+ return false
335
+ }
336
+
337
+ /** Step over comments that sit directly before a type atom. */
338
+ private skipCommentsBeforeType(): void {
339
+ this.pos = this.nextMeaningful(this.pos)
340
+ }
341
+
342
+ private collectJSDoc(): string | undefined {
343
+ // Look backwards from current pos for a preceding JSDoc comment
344
+ let idx = this.pos - 1
345
+ while (idx >= 0) {
346
+ const t = this.tokens[idx]
347
+ if (!t) break
348
+ if (t.kind === 'multiline_comment' && t.value.startsWith('/**')) {
349
+ // Extract text from JSDoc
350
+ return (
351
+ t.value
352
+ .replace(/^\/\*\*\s*/, '')
353
+ .replace(/\s*\*\/$/, '')
354
+ .split('\n')
355
+ .map((l) => l.replace(/^\s*\*\s?/, '').trim())
356
+ .filter((l) => l.length > 0 && !l.startsWith('@'))
357
+ .join(' ')
358
+ .trim() || undefined
359
+ )
360
+ }
361
+ // Allow skipping over single-line comments before a JSDoc
362
+ if (t.kind !== 'comment') break
363
+ idx--
364
+ }
365
+ return undefined
366
+ }
367
+
368
+ // -- Top-level parsing -----------------------------------------------------
369
+
370
+ private parse(): void {
371
+ while (this.pos < this.tokens.length) {
372
+ const t = this.peek()
373
+ if (!t) break
374
+
375
+ if (t.kind === 'word' && t.value === 'export') {
376
+ const savedPos = this.pos
377
+ this.advance()
378
+ const next = this.peek()
379
+ if (next?.kind === 'word' && next.value === 'type') {
380
+ this.advance()
381
+ try {
382
+ this.parseTypeAlias()
383
+ } catch {
384
+ // Skip unparseable type alias — restore and skip to next export
385
+ this.pos = savedPos + 1
386
+ }
387
+ continue
388
+ }
389
+ if (next?.kind === 'word' && next.value === 'interface') {
390
+ this.advance()
391
+ try {
392
+ this.parseInterface()
393
+ } catch {
394
+ // Skip unparseable interface — restore and skip to next export
395
+ this.pos = savedPos + 1
396
+ }
397
+ continue
398
+ }
399
+ }
400
+
401
+ this.advance() // skip token
402
+ }
403
+ }
404
+
405
+ private parseTypeAlias(): void {
406
+ const nameTok = this.advance()
407
+ if (!nameTok || nameTok.kind !== 'word') return
408
+ const name = nameTok.value
409
+ const description = this.collectJSDoc()
410
+
411
+ // Handle generics: skip <T, ...>
412
+ if (this.is('symbol', '<')) {
413
+ this.skipBalanced('<', '>')
414
+ }
415
+
416
+ this.expect('symbol', '=')
417
+ const expr = this.parseTypeExpr()
418
+ this.defs.set(name, { name, expr, description })
419
+ }
420
+
421
+ private parseInterface(): void {
422
+ const nameTok = this.advance()
423
+ if (!nameTok || nameTok.kind !== 'word') return
424
+ const name = nameTok.value
425
+ const description = this.collectJSDoc()
426
+
427
+ // Handle generics
428
+ if (this.is('symbol', '<')) {
429
+ this.skipBalanced('<', '>')
430
+ }
431
+
432
+ // Handle extends
433
+ if (this.is('word', 'extends')) {
434
+ this.advance()
435
+ while (!this.is('symbol', '{')) this.advance()
436
+ }
437
+
438
+ const properties = this.parseObjectBody()
439
+ this.defs.set(name, { name, expr: { kind: 'object', properties }, description })
440
+ }
441
+
442
+ // -- Type expression parsing -----------------------------------------------
443
+
444
+ private parseTypeExpr(): TypeExpr {
445
+ // Handle leading pipe: | 'a' | 'b' | 'c' (common in multi-line union types)
446
+ if (this.is('symbol', '|')) {
447
+ const members: TypeExpr[] = []
448
+ while (this.matchMeaningful('symbol', '|')) {
449
+ this.skipCommentsBeforeType()
450
+ members.push(this.parsePrimaryType())
451
+ }
452
+ let expr: TypeExpr =
453
+ members.length === 1 ? (members[0] as TypeExpr) : { kind: 'union', members }
454
+ // Handle array suffix: T[]
455
+ while (
456
+ this.is('symbol', '[') &&
457
+ this.peek(1)?.kind === 'symbol' &&
458
+ this.peek(1)?.value === ']'
459
+ ) {
460
+ this.advance()
461
+ this.advance()
462
+ expr = { kind: 'array', element: expr }
463
+ }
464
+ return expr
465
+ }
466
+
467
+ let expr = this.parsePrimaryType()
468
+
469
+ // Handle union: T | U | V — a member may carry its own JSDoc, so look past
470
+ // comments for the `|`, but only consume them once one is actually found.
471
+ if (this.isMeaningful('symbol', '|')) {
472
+ const members: TypeExpr[] = [expr]
473
+ while (this.matchMeaningful('symbol', '|')) {
474
+ this.skipCommentsBeforeType()
475
+ members.push(this.parsePrimaryType())
476
+ }
477
+ expr = { kind: 'union', members }
478
+ }
479
+
480
+ // Handle intersection: T & U (treat as first type for schema purposes)
481
+ if (this.is('symbol', '&')) {
482
+ while (this.match('symbol', '&')) {
483
+ this.parsePrimaryType() // skip intersected types
484
+ }
485
+ }
486
+
487
+ // Handle array suffix: T[]
488
+ while (
489
+ this.is('symbol', '[') &&
490
+ this.peek(1)?.kind === 'symbol' &&
491
+ this.peek(1)?.value === ']'
492
+ ) {
493
+ this.advance() // [
494
+ this.advance() // ]
495
+ expr = { kind: 'array', element: expr }
496
+ }
497
+
498
+ return expr
499
+ }
500
+
501
+ private parsePrimaryType(): TypeExpr {
502
+ const t = this.peek()
503
+ if (!t) return { kind: 'primitive', value: 'unknown' }
504
+
505
+ // String literal
506
+ if (t.kind === 'string') {
507
+ this.advance()
508
+ const val = t.value.slice(1, -1) // strip quotes
509
+ return { kind: 'literal', value: val }
510
+ }
511
+
512
+ // Inline object type
513
+ if (t.kind === 'symbol' && t.value === '{') {
514
+ return this.parseInlineObject()
515
+ }
516
+
517
+ // Parenthesized type or function type: (args) => ReturnType
518
+ if (t.kind === 'symbol' && t.value === '(') {
519
+ // Peek ahead to detect function type: skip balanced parens then check for =>
520
+ const savedPos = this.pos
521
+ this.skipBalanced('(', ')')
522
+ if (
523
+ this.is('symbol', '=') &&
524
+ this.peek(1)?.kind === 'symbol' &&
525
+ this.peek(1)?.value === '>'
526
+ ) {
527
+ // Function type — skip return type and represent as unknown
528
+ this.advance() // =
529
+ this.advance() // >
530
+ this.parseTypeExpr() // skip return type
531
+ return { kind: 'primitive', value: 'unknown' }
532
+ }
533
+ // Not a function type — backtrack and parse as grouped type
534
+ this.pos = savedPos
535
+ this.advance() // (
536
+ const inner = this.parseTypeExpr()
537
+ this.expect('symbol', ')')
538
+ // Handle array suffix after parens
539
+ while (
540
+ this.is('symbol', '[') &&
541
+ this.peek(1)?.kind === 'symbol' &&
542
+ this.peek(1)?.value === ']'
543
+ ) {
544
+ this.advance()
545
+ this.advance()
546
+ return { kind: 'array', element: inner }
547
+ }
548
+ return inner
549
+ }
550
+
551
+ // Array<T>
552
+ if (t.kind === 'word' && t.value === 'Array') {
553
+ this.advance()
554
+ this.expect('symbol', '<')
555
+ const element = this.parseTypeExpr()
556
+ this.expect('symbol', '>')
557
+ return { kind: 'array', element }
558
+ }
559
+
560
+ // Record<string, T>
561
+ if (t.kind === 'word' && t.value === 'Record') {
562
+ this.advance()
563
+ this.expect('symbol', '<')
564
+ this.parseTypeExpr() // key type (skip)
565
+ this.expect('symbol', ',')
566
+ const valueType = this.parseTypeExpr()
567
+ this.expect('symbol', '>')
568
+ return { kind: 'record', valueType }
569
+ }
570
+
571
+ // Partial<T>
572
+ if (t.kind === 'word' && t.value === 'Partial') {
573
+ this.advance()
574
+ this.expect('symbol', '<')
575
+ const inner = this.parseTypeExpr()
576
+ this.expect('symbol', '>')
577
+ return { kind: 'partial', inner }
578
+ }
579
+
580
+ // Primitives
581
+ if (t.kind === 'word') {
582
+ const val = t.value
583
+ if (val === 'string' || val === 'number' || val === 'boolean') {
584
+ this.advance()
585
+ // Handle array suffix
586
+ while (this.is('symbol', '[') && this.peek(1)?.value === ']') {
587
+ this.advance()
588
+ this.advance()
589
+ return { kind: 'array', element: { kind: 'primitive', value: val } }
590
+ }
591
+ return { kind: 'primitive', value: val }
592
+ }
593
+ if (
594
+ val === 'unknown' ||
595
+ val === 'any' ||
596
+ val === 'never' ||
597
+ val === 'void' ||
598
+ val === 'undefined' ||
599
+ val === 'null'
600
+ ) {
601
+ this.advance()
602
+ return { kind: 'primitive', value: 'unknown' }
603
+ }
604
+ // typeof operator — skip and treat as unknown
605
+ if (val === 'typeof') {
606
+ this.advance()
607
+ // Skip the expression after typeof
608
+ while (this.is('word') || this.is('symbol', '.') || this.is('symbol', '[')) {
609
+ if (this.is('symbol', '[')) {
610
+ this.skipBalanced('[', ']')
611
+ } else {
612
+ this.advance()
613
+ }
614
+ }
615
+ return { kind: 'primitive', value: 'unknown' }
616
+ }
617
+ // keyof operator — skip and treat as string
618
+ if (val === 'keyof') {
619
+ this.advance()
620
+ this.parsePrimaryType() // skip the type after keyof
621
+ return { kind: 'primitive', value: 'string' }
622
+ }
623
+ // Named type reference
624
+ this.advance()
625
+ // Handle generics on reference: SomeType<T>
626
+ if (this.is('symbol', '<')) {
627
+ this.skipBalanced('<', '>')
628
+ }
629
+ // Handle array suffix
630
+ while (this.is('symbol', '[') && this.peek(1)?.value === ']') {
631
+ this.advance()
632
+ this.advance()
633
+ return { kind: 'array', element: { kind: 'reference', name: val } }
634
+ }
635
+ return { kind: 'reference', name: val }
636
+ }
637
+
638
+ // Number literal (skip)
639
+ if (t.kind === 'number') {
640
+ this.advance()
641
+ return { kind: 'primitive', value: 'number' }
642
+ }
643
+
644
+ this.advance()
645
+ return { kind: 'primitive', value: 'unknown' }
646
+ }
647
+
648
+ private parseInlineObject(): TypeExpr {
649
+ const properties = this.parseObjectBody()
650
+ return { kind: 'object', properties }
651
+ }
652
+
653
+ private parseObjectBody(): ParsedProperty[] {
654
+ this.expect('symbol', '{')
655
+ const properties: ParsedProperty[] = []
656
+
657
+ while (!this.is('symbol', '}') && this.pos < this.tokens.length) {
658
+ // Collect JSDoc/comments above property
659
+ let description: string | undefined
660
+ while (this.peek()?.kind === 'comment' || this.peek()?.kind === 'multiline_comment') {
661
+ const commentTok = this.advance()
662
+ if (commentTok.kind === 'multiline_comment' && commentTok.value.startsWith('/**')) {
663
+ description =
664
+ commentTok.value
665
+ .replace(/^\/\*\*\s*/, '')
666
+ .replace(/\s*\*\/$/, '')
667
+ .split('\n')
668
+ .map((l) => l.replace(/^\s*\*\s?/, '').trim())
669
+ .filter((l) => l.length > 0 && !l.startsWith('@'))
670
+ .join(' ')
671
+ .trim() || undefined
672
+ } else if (commentTok.kind === 'comment') {
673
+ const text = commentTok.value.replace(/^\/\/\s*/, '').trim()
674
+ if (text) description = text
675
+ }
676
+ }
677
+
678
+ // Skip semicolons
679
+ if (this.is('symbol', ';')) {
680
+ this.advance()
681
+ continue
682
+ }
683
+
684
+ // End of object
685
+ if (this.is('symbol', '}')) break
686
+
687
+ // Index signature: [key: string]: ValueType
688
+ if (this.is('symbol', '[')) {
689
+ this.skipBalanced('[', ']')
690
+ this.expect('symbol', ':')
691
+ this.parseTypeExpr() // skip index signature value type
692
+ this.match('symbol', ';')
693
+ continue
694
+ }
695
+
696
+ // Property name
697
+ const nameTok = this.peek()
698
+ if (!nameTok || nameTok.kind !== 'word') {
699
+ this.advance()
700
+ continue
701
+ }
702
+ this.advance()
703
+ const propName = nameTok.value
704
+
705
+ // Optional marker
706
+ const optional = this.match('symbol', '?')
707
+
708
+ // Colon
709
+ if (!this.match('symbol', ':')) {
710
+ // Could be a method signature — skip to semicolon or closing brace
711
+ while (
712
+ !this.is('symbol', ';') &&
713
+ !this.is('symbol', '}') &&
714
+ this.pos < this.tokens.length
715
+ ) {
716
+ this.advance()
717
+ }
718
+ this.match('symbol', ';')
719
+ continue
720
+ }
721
+
722
+ const typeExpr = this.parseTypeExpr()
723
+
724
+ // Skip trailing semicolon/comma
725
+ this.match('symbol', ';')
726
+ this.match('symbol', ',')
727
+
728
+ properties.push({ name: propName, optional, typeExpr, description })
729
+ }
730
+
731
+ this.expect('symbol', '}')
732
+ return properties
733
+ }
734
+
735
+ private skipBalanced(open: string, close: string): void {
736
+ this.expect('symbol', open)
737
+ let depth = 1
738
+ while (depth > 0 && this.pos < this.tokens.length) {
739
+ const t = this.advance()
740
+ if (t.kind === 'symbol' && t.value === open) depth++
741
+ if (t.kind === 'symbol' && t.value === close) depth--
742
+ }
743
+ }
744
+ }
745
+
746
+ // ---------------------------------------------------------------------------
747
+ // TypeExpr → JSON Schema conversion (recursive, with reference resolution)
748
+ // ---------------------------------------------------------------------------
749
+ class SchemaGenerator {
750
+ private parser: TypeParser
751
+ private resolving: Set<string> = new Set() // cycle guard
752
+
753
+ constructor(parser: TypeParser) {
754
+ this.parser = parser
755
+ }
756
+
757
+ typeExprToSchema(expr: TypeExpr): SchemaNode {
758
+ switch (expr.kind) {
759
+ case 'primitive':
760
+ if (expr.value === 'unknown' || expr.value === 'any') return {}
761
+ return { type: expr.value }
762
+
763
+ case 'literal':
764
+ return { type: 'string', enum: [expr.value] }
765
+
766
+ case 'union':
767
+ return this.unionToSchema(expr.members)
768
+
769
+ case 'array':
770
+ return { type: 'array', items: this.typeExprToSchema(expr.element) }
771
+
772
+ case 'object':
773
+ return this.objectToSchema(expr.properties)
774
+
775
+ case 'record':
776
+ return { type: 'object', additionalProperties: this.typeExprToSchema(expr.valueType) }
777
+
778
+ case 'partial': {
779
+ const inner = this.typeExprToSchema(expr.inner)
780
+ // Partial makes all required fields optional
781
+ const result = { ...inner }
782
+ // biome-ignore lint/performance/noDelete: must remove the JSON-schema key entirely (undefined would still serialize the property)
783
+ delete result.required
784
+ return result
785
+ }
786
+
787
+ case 'reference':
788
+ return this.resolveReference(expr.name)
789
+
790
+ case 'tuple':
791
+ return {
792
+ type: 'array',
793
+ items: this.typeExprToSchema(expr.elements[0] ?? { kind: 'primitive', value: 'unknown' }),
794
+ }
795
+ }
796
+ }
797
+
798
+ private unionToSchema(members: TypeExpr[]): SchemaNode {
799
+ // Filter out null/undefined
800
+ const filtered = members.filter((m) => !(m.kind === 'primitive' && m.value === 'unknown'))
801
+ if (filtered.length === 0) return {}
802
+ if (filtered.length === 1) return this.typeExprToSchema(filtered[0] as TypeExpr)
803
+
804
+ // Check if all members are string literals → enum
805
+ const allLiterals = filtered.every((m) => m.kind === 'literal')
806
+ if (allLiterals) {
807
+ const values = filtered.map((m) => (m as { kind: 'literal'; value: string }).value)
808
+ return { type: 'string', enum: values }
809
+ }
810
+
811
+ // Check if all members are the same primitive
812
+ const allSamePrimitive = filtered.every(
813
+ (m) =>
814
+ m.kind === 'primitive' &&
815
+ m.value === (filtered[0] as { kind: 'primitive'; value: string }).value
816
+ )
817
+ if (allSamePrimitive && filtered[0]?.kind === 'primitive') {
818
+ return { type: filtered[0].value }
819
+ }
820
+
821
+ // Mixed union — use anyOf
822
+ const schemas = filtered.map((m) => this.typeExprToSchema(m))
823
+ // Deduplicate simple schemas
824
+ const unique = this.deduplicateSchemas(schemas)
825
+ if (unique.length === 1) return unique[0] as SchemaNode
826
+ return { anyOf: unique }
827
+ }
828
+
829
+ private deduplicateSchemas(schemas: SchemaNode[]): SchemaNode[] {
830
+ const seen = new Set<string>()
831
+ const result: SchemaNode[] = []
832
+ for (const s of schemas) {
833
+ const key = JSON.stringify(s)
834
+ if (!seen.has(key)) {
835
+ seen.add(key)
836
+ result.push(s)
837
+ }
838
+ }
839
+ return result
840
+ }
841
+
842
+ private objectToSchema(properties: ParsedProperty[]): SchemaNode {
843
+ const props: Record<string, SchemaNode> = {}
844
+ const required: string[] = []
845
+
846
+ for (const prop of properties) {
847
+ const schema = this.typeExprToSchema(prop.typeExpr)
848
+ if (prop.description) {
849
+ schema.description = prop.description
850
+ }
851
+ props[prop.name] = schema
852
+ if (!prop.optional) {
853
+ required.push(prop.name)
854
+ }
855
+ }
856
+
857
+ const result: SchemaNode = { type: 'object', properties: props }
858
+ if (required.length > 0) {
859
+ result.required = required
860
+ }
861
+ return result
862
+ }
863
+
864
+ resolveReference(name: string): SchemaNode {
865
+ // Cycle guard
866
+ if (this.resolving.has(name)) {
867
+ return { type: 'object' }
868
+ }
869
+ this.resolving.add(name)
870
+
871
+ const def = this.parser.getDefinition(name)
872
+ if (!def) {
873
+ this.resolving.delete(name)
874
+ // Fallback: could be an external type we don't know about
875
+ return { type: 'string' }
876
+ }
877
+
878
+ const result = this.typeExprToSchema(def.expr)
879
+ if (def.description && !result.description) {
880
+ result.description = def.description
881
+ }
882
+ this.resolving.delete(name)
883
+ return result
884
+ }
885
+ }
886
+
887
+ // ---------------------------------------------------------------------------
888
+ // Schema generators for each output file
889
+ // ---------------------------------------------------------------------------
890
+
891
+ function generateNucleusTableSchema(gen: SchemaGenerator, parser: TypeParser): JsonSchema {
892
+ const tableDef = parser.getDefinition('NucleusTable')
893
+ if (!tableDef) throw new Error('NucleusTable not found in types.ts')
894
+
895
+ const tableSchema = gen.typeExprToSchema(tableDef.expr) as JsonSchema
896
+
897
+ // Collect $defs from sub-interfaces that are referenced by NucleusTable
898
+ const defs: Record<string, SchemaNode> = {}
899
+ const subTypes = [
900
+ 'NucleusColumn',
901
+ 'NucleusIndex',
902
+ 'NucleusConstraints',
903
+ 'NucleusUniqueConstraint',
904
+ 'NucleusCheckConstraint',
905
+ 'NucleusColumnReference',
906
+ 'NucleusColumnEnum',
907
+ 'NucleusColumnValidation',
908
+ ]
909
+
910
+ const defNameMap: Record<string, string> = {
911
+ NucleusColumn: 'column',
912
+ NucleusIndex: 'index',
913
+ NucleusConstraints: 'constraints',
914
+ NucleusUniqueConstraint: 'uniqueConstraint',
915
+ NucleusCheckConstraint: 'checkConstraint',
916
+ NucleusColumnReference: 'columnReference',
917
+ NucleusColumnEnum: 'columnEnum',
918
+ NucleusColumnValidation: 'columnValidation',
919
+ }
920
+
921
+ for (const typeName of subTypes) {
922
+ const def = parser.getDefinition(typeName)
923
+ if (def) {
924
+ const shortName = defNameMap[typeName] ?? typeName
925
+ defs[shortName] = gen.typeExprToSchema(def.expr)
926
+ }
927
+ }
928
+
929
+ // Replace inline expansions of known sub-types with $ref
930
+ if (tableSchema.properties) {
931
+ replaceWithRefs(tableSchema.properties, defs, defNameMap)
932
+ }
933
+
934
+ return {
935
+ $id: 'table.schema.json',
936
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
937
+ title: 'Nucleus Table Definition',
938
+ description: 'Generated from NucleusTable interface in types.ts',
939
+ type: 'object',
940
+ properties: {
941
+ ...tableSchema.properties,
942
+ },
943
+ required: tableSchema.required ?? ['table_name'],
944
+ additionalProperties: false,
945
+ $defs: defs,
946
+ }
947
+ }
948
+
949
+ function replaceWithRefs(
950
+ props: Record<string, SchemaNode>,
951
+ defs: Record<string, SchemaNode>,
952
+ nameMap: Record<string, string>
953
+ ): void {
954
+ const reverseMap: Record<string, string> = {}
955
+ for (const [full, short] of Object.entries(nameMap)) {
956
+ reverseMap[full] = short
957
+ }
958
+
959
+ for (const [key, schema] of Object.entries(props)) {
960
+ // If this property's schema matches a known $def, replace with $ref
961
+ for (const [, shortName] of Object.entries(nameMap)) {
962
+ if (shortName && defs[shortName]) {
963
+ const defStr = JSON.stringify(defs[shortName])
964
+ const schemaStr = JSON.stringify(schema)
965
+ if (schemaStr === defStr) {
966
+ props[key] = { $ref: `#/$defs/${shortName}` }
967
+ break
968
+ }
969
+ // Check if it's an array of this type
970
+ if (schema.type === 'array' && schema.items) {
971
+ const itemsStr = JSON.stringify(schema.items)
972
+ if (itemsStr === defStr) {
973
+ schema.items = { $ref: `#/$defs/${shortName}` }
974
+ }
975
+ }
976
+ }
977
+ }
978
+ }
979
+ }
980
+
981
+ // ---------------------------------------------------------------------------
982
+ // Auto-deduplication: detect repeated object schemas and extract into $defs
983
+ // ---------------------------------------------------------------------------
984
+
985
+ type SchemaPath = { obj: Record<string, SchemaNode>; key: string; fullPath: string }
986
+
987
+ function collectObjectSchemas(
988
+ node: SchemaNode,
989
+ parentObj: Record<string, SchemaNode> | null,
990
+ parentKey: string | null,
991
+ pathPrefix: string,
992
+ results: Map<string, { hash: string; path: string; locations: SchemaPath[] }>
993
+ ): void {
994
+ if (!node || typeof node !== 'object') return
995
+
996
+ // Only deduplicate object schemas with 3+ properties (worth extracting)
997
+ if (node.type === 'object' && node.properties && Object.keys(node.properties).length >= 3) {
998
+ // Create a canonical hash (without description to match structurally identical schemas)
999
+ const canonical = { ...node }
1000
+ // biome-ignore lint/performance/noDelete: must drop the key for structural hashing (undefined would still appear in the canonical shape)
1001
+ delete canonical.description
1002
+ const hash = JSON.stringify(canonical)
1003
+
1004
+ const existing = results.get(hash)
1005
+ if (!existing) {
1006
+ results.set(hash, { hash, path: pathPrefix, locations: [] })
1007
+ }
1008
+ if (parentObj && parentKey) {
1009
+ ;(results.get(hash) as { locations: SchemaPath[] }).locations.push({
1010
+ obj: parentObj,
1011
+ key: parentKey,
1012
+ fullPath: pathPrefix,
1013
+ })
1014
+ }
1015
+ }
1016
+
1017
+ // Recurse into properties
1018
+ if (node.properties) {
1019
+ for (const [key, child] of Object.entries(node.properties)) {
1020
+ collectObjectSchemas(child, node.properties, key, `${pathPrefix}.${key}`, results)
1021
+ }
1022
+ }
1023
+
1024
+ // Recurse into array items
1025
+ if (node.type === 'array' && node.items && typeof node.items === 'object') {
1026
+ collectObjectSchemas(node.items, null, null, `${pathPrefix}[]`, results)
1027
+ if (node.items.properties) {
1028
+ for (const [key, child] of Object.entries(node.items.properties)) {
1029
+ collectObjectSchemas(child, node.items.properties, key, `${pathPrefix}[].${key}`, results)
1030
+ }
1031
+ }
1032
+ }
1033
+
1034
+ // Recurse into anyOf
1035
+ if (node.anyOf) {
1036
+ for (let i = 0; i < node.anyOf.length; i++) {
1037
+ collectObjectSchemas(
1038
+ node.anyOf[i] as SchemaNode,
1039
+ null,
1040
+ null,
1041
+ `${pathPrefix}.anyOf[${i}]`,
1042
+ results
1043
+ )
1044
+ }
1045
+ }
1046
+ }
1047
+
1048
+ function deriveDefName(locations: SchemaPath[], schema: SchemaNode): string {
1049
+ const keys = locations.map((l) => l.key)
1050
+ const fullPaths = locations.map((l) => l.fullPath)
1051
+ const propKeys = schema.properties ? Object.keys(schema.properties) : []
1052
+
1053
+ // ---- Heuristic 1: name by schema content shape ----
1054
+ // Token configs: secret + expiresIn + algorithm
1055
+ if (
1056
+ propKeys.includes('secret') &&
1057
+ propKeys.includes('expiresIn') &&
1058
+ propKeys.includes('algorithm')
1059
+ ) {
1060
+ return 'tokenConfig'
1061
+ }
1062
+ // OAuth provider: clientId + clientSecret + redirectUri
1063
+ if (
1064
+ propKeys.includes('clientId') &&
1065
+ propKeys.includes('clientSecret') &&
1066
+ propKeys.includes('redirectUri')
1067
+ ) {
1068
+ return 'oauthProvider'
1069
+ }
1070
+ // Rate limit rule: window + max
1071
+ if (propKeys.includes('window') && propKeys.includes('max')) {
1072
+ if (propKeys.includes('blockDuration')) return 'rateLimitRule'
1073
+ return 'rateLimitWindow'
1074
+ }
1075
+ // Endpoint config: enabled + basePath
1076
+ if (propKeys.length <= 3 && propKeys.includes('enabled') && propKeys.includes('basePath')) {
1077
+ return 'endpointConfig'
1078
+ }
1079
+
1080
+ // ---- Heuristic 2: content-based — route + isPublic + enabled pattern ----
1081
+ if (propKeys.includes('route') && propKeys.includes('isPublic') && propKeys.includes('enabled')) {
1082
+ return 'authRoute'
1083
+ }
1084
+
1085
+ // ---- Heuristic 3: common parent context ----
1086
+ // All under the same parent (e.g. authentication.providers.*) → use parent segment
1087
+ const parents = fullPaths.map((p) => {
1088
+ const parts = p.split('.')
1089
+ parts.pop()
1090
+ return parts.pop() ?? ''
1091
+ })
1092
+ const allSameParent = parents.every((p) => p === parents[0])
1093
+ if (allSameParent && parents[0]) {
1094
+ const parent = parents[0]
1095
+ return parent.endsWith('s') ? parent.slice(0, -1) : parent
1096
+ }
1097
+
1098
+ // ---- Heuristic 4: common suffix ----
1099
+ const commonSuffix = findCommonSuffix(keys)
1100
+ if (commonSuffix && commonSuffix.length > 2) {
1101
+ return `${commonSuffix.charAt(0).toLowerCase() + commonSuffix.slice(1)}Config`
1102
+ }
1103
+
1104
+ // Fallback: first key
1105
+ return keys[0] ?? 'unnamed'
1106
+ }
1107
+
1108
+ function deduplicateConfigSchema(schema: JsonSchema): Record<string, SchemaNode> {
1109
+ const defs: Record<string, SchemaNode> = {}
1110
+ if (!schema.properties) return defs
1111
+
1112
+ const schemaMap = new Map<string, { hash: string; path: string; locations: SchemaPath[] }>()
1113
+
1114
+ // Collect all object schemas with their locations
1115
+ for (const [key, child] of Object.entries(schema.properties)) {
1116
+ collectObjectSchemas(child, schema.properties, key, key, schemaMap)
1117
+ }
1118
+
1119
+ // Find duplicates (2+ occurrences) and extract into $defs
1120
+ const usedNames = new Set<string>()
1121
+
1122
+ for (const [hash, entry] of schemaMap.entries()) {
1123
+ if (entry.locations.length < 2) continue
1124
+
1125
+ const defSchema = JSON.parse(hash) as SchemaNode
1126
+ const baseName = deriveDefName(entry.locations, defSchema)
1127
+
1128
+ // Ensure unique name
1129
+ let defName = baseName
1130
+ let counter = 1
1131
+ while (usedNames.has(defName)) {
1132
+ defName = `${baseName}${counter++}`
1133
+ }
1134
+ usedNames.add(defName)
1135
+
1136
+ defs[defName] = defSchema
1137
+
1138
+ // Replace all occurrences with $ref
1139
+ for (const loc of entry.locations) {
1140
+ const original = loc.obj[loc.key]
1141
+ const ref: SchemaNode = { $ref: `#/$defs/${defName}` }
1142
+ if (original?.description) {
1143
+ ref.description = original.description
1144
+ }
1145
+ loc.obj[loc.key] = ref
1146
+ }
1147
+ }
1148
+
1149
+ return defs
1150
+ }
1151
+
1152
+ function findCommonSuffix(words: string[]): string {
1153
+ if (words.length === 0) return ''
1154
+ const splitCamel = (s: string) => s.replace(/([a-z])([A-Z])/g, '$1 $2').split(' ')
1155
+ const parts = words.map(splitCamel)
1156
+ const minLen = Math.min(...parts.map((p) => p.length))
1157
+
1158
+ const common: string[] = []
1159
+ for (let i = 1; i <= minLen; i++) {
1160
+ const suffix = parts[0]?.[parts[0].length - i]?.toLowerCase()
1161
+ if (suffix && parts.every((p) => p[p.length - i]?.toLowerCase() === suffix)) {
1162
+ common.unshift(suffix)
1163
+ } else {
1164
+ break
1165
+ }
1166
+ }
1167
+
1168
+ return common.map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join('')
1169
+ }
1170
+
1171
+ function generateNucleusConfigSchema(gen: SchemaGenerator, parser: TypeParser): JsonSchema {
1172
+ const configDef = parser.getDefinition('NucleusConfigOptions')
1173
+ if (!configDef) throw new Error('NucleusConfigOptions not found in types.ts')
1174
+
1175
+ const configSchema = gen.typeExprToSchema(configDef.expr) as JsonSchema
1176
+
1177
+ // Add $schema property for config files
1178
+ if (configSchema.properties) {
1179
+ configSchema.properties = {
1180
+ $schema: { type: 'string', description: 'JSON Schema reference' },
1181
+ ...configSchema.properties,
1182
+ }
1183
+ }
1184
+
1185
+ // The entities field should reference table.schema.json
1186
+ if (configSchema.properties?.entities) {
1187
+ configSchema.properties.entities = {
1188
+ type: 'array',
1189
+ description: 'Entity/table definitions',
1190
+ items: { $ref: 'table.schema.json' },
1191
+ }
1192
+ }
1193
+
1194
+ // externalEntities in authorization should also reference table.schema.json
1195
+ if (configSchema.properties?.authorization?.properties?.externalEntities) {
1196
+ configSchema.properties.authorization.properties.externalEntities = {
1197
+ type: 'array',
1198
+ description: 'Entity definitions from external consumer services',
1199
+ items: { $ref: 'table.schema.json' },
1200
+ }
1201
+ }
1202
+
1203
+ // Auto-deduplicate repeated inline schemas into $defs
1204
+ const defs = deduplicateConfigSchema(configSchema)
1205
+
1206
+ const result: JsonSchema = {
1207
+ $id: 'config.nucleus.json',
1208
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
1209
+ title: 'Nucleus Config',
1210
+ description: 'Generated from NucleusConfigOptions interface in types.ts',
1211
+ type: 'object',
1212
+ properties: configSchema.properties,
1213
+ required: configSchema.required ?? ['appId', 'entities'],
1214
+ additionalProperties: false,
1215
+ }
1216
+
1217
+ if (Object.keys(defs).length > 0) {
1218
+ result.$defs = defs
1219
+ console.log(` Extracted ${Object.keys(defs).length} $defs: ${Object.keys(defs).join(', ')}`)
1220
+ }
1221
+
1222
+ return result
1223
+ }
1224
+
1225
+ function generateTablesArraySchema(): JsonSchema {
1226
+ return {
1227
+ $id: 'nucleus.tables.schema.json',
1228
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
1229
+ title: 'Nucleus Tables Array',
1230
+ description: 'Array of Nucleus table definitions',
1231
+ type: 'object',
1232
+ properties: {
1233
+ $schema: { type: 'string' },
1234
+ tables: {
1235
+ type: 'array',
1236
+ items: { $ref: 'table.schema.json' },
1237
+ },
1238
+ },
1239
+ required: ['tables'],
1240
+ }
1241
+ }
1242
+
1243
+ // ---------------------------------------------------------------------------
1244
+ // Main
1245
+ // ---------------------------------------------------------------------------
1246
+ function main() {
1247
+ console.log('Reading types.ts and imported files...')
1248
+ const sources = loadSources()
1249
+ console.log(` Loaded ${sources.length} source file(s)`)
1250
+
1251
+ console.log('Parsing type definitions...')
1252
+ const parser = new TypeParser(sources)
1253
+ console.log(` Found ${parser.getAllDefs().size} type definitions`)
1254
+
1255
+ const gen = new SchemaGenerator(parser)
1256
+
1257
+ console.log('Generating table.schema.json...')
1258
+ const tableSchema = generateNucleusTableSchema(gen, parser)
1259
+ fs.writeFileSync(
1260
+ path.join(SCHEMAS_DIR, 'table.schema.json'),
1261
+ `${JSON.stringify(tableSchema, null, 2)}\n`
1262
+ )
1263
+
1264
+ console.log('Generating config.nucleus.json...')
1265
+ const configSchema = generateNucleusConfigSchema(gen, parser)
1266
+ fs.writeFileSync(
1267
+ path.join(SCHEMAS_DIR, 'config.nucleus.json'),
1268
+ `${JSON.stringify(configSchema, null, 2)}\n`
1269
+ )
1270
+
1271
+ console.log('Generating nucleus.tables.schema.json...')
1272
+ const tablesSchema = generateTablesArraySchema()
1273
+ fs.writeFileSync(
1274
+ path.join(SCHEMAS_DIR, 'nucleus.tables.schema.json'),
1275
+ `${JSON.stringify(tablesSchema, null, 2)}\n`
1276
+ )
1277
+
1278
+ console.log('Schemas generated successfully!')
1279
+ console.log(` - ${SCHEMAS_DIR}/table.schema.json`)
1280
+ console.log(` - ${SCHEMAS_DIR}/config.nucleus.json`)
1281
+ console.log(` - ${SCHEMAS_DIR}/nucleus.tables.schema.json`)
1282
+ }
1283
+
1284
+ main()