ramdb2-cli 0.0.0-stage → 2.0.0-alpha.1

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.
@@ -0,0 +1,165 @@
1
+ // infra.yaml (D55): the backups, the servers and their sites. Read, checked, with every path made absolute.
2
+ import { existsSync, readFileSync } from 'node:fs'
3
+ import { dirname, join, resolve } from 'node:path'
4
+ import { parse } from 'yaml'
5
+
6
+ const NAME = /^[a-z][a-z0-9-]*$/
7
+ const DOMAIN = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/
8
+ const MEMORY = /^\d+[kmg]$/
9
+
10
+ export class InfraError extends Error {
11
+ constructor(errors) {
12
+ super(`infra.yaml is not valid:\n${errors.map(error => ` - ${error}`).join('\n')}`)
13
+ this.name = 'InfraError'
14
+ this.errors = errors
15
+ }
16
+ }
17
+
18
+ /**
19
+ * @typedef {object} Site
20
+ * @property {string} name unique on all the servers
21
+ * @property {string} source the absolute path of the ramdb2 project
22
+ * @property {boolean} withClient a project of `new --with-client`: server/ and web/
23
+ * @property {string} domain
24
+ * @property {string[]} aliases
25
+ * @property {string | undefined} memory
26
+ *
27
+ * @typedef {object} Custom a site maintained by hand
28
+ * @property {string} name
29
+ * @property {string} nginx the absolute path of its nginx configuration
30
+ * @property {string | undefined} compose the absolute path of its compose file, if any
31
+ * @property {string[]} domains the domains whose certificates certbot keeps
32
+ *
33
+ * @typedef {object} Server
34
+ * @property {string} name
35
+ * @property {string} host
36
+ * @property {string} email
37
+ * @property {Site[]} sites
38
+ * @property {Custom[]} custom
39
+ *
40
+ * @typedef {object} Infra
41
+ * @property {string} dir the folder of infra.yaml
42
+ * @property {{target: string}} backup
43
+ * @property {Server[]} servers
44
+ */
45
+
46
+ /**
47
+ * Reads and checks infra.yaml. All the errors are reported at once.
48
+ * @param {string} file
49
+ * @returns {Infra}
50
+ */
51
+ export function readInfra(file) {
52
+ const dir = dirname(resolve(file))
53
+ let raw
54
+ try {
55
+ raw = parse(readFileSync(file, 'utf8'))
56
+ } catch (error) {
57
+ throw new InfraError([error.code === 'ENOENT' ? `${file} not found` : error.message])
58
+ }
59
+ const errors = []
60
+ const check = (condition, message) => {
61
+ if (!condition) errors.push(message)
62
+ return condition
63
+ }
64
+ if (!check(isObject(raw), 'expected an object with backup and servers')) throw new InfraError(errors)
65
+ unknownKeys(raw, ['backup', 'servers'], '', errors)
66
+
67
+ const backup = { target: raw.backup?.target }
68
+ if (check(isObject(raw.backup), 'backup: required, with target')) {
69
+ unknownKeys(raw.backup, ['target'], 'backup.', errors)
70
+ check(typeof backup.target === 'string' && /^sftp:\/\/[^@/]+@[^/]+(\/.*)?$/.test(backup.target),
71
+ 'backup.target: sftp://user@host[:port]/path')
72
+ }
73
+
74
+ const servers = []
75
+ const siteNames = new Map()
76
+ const domains = new Map()
77
+ const claim = (domain, owner) => {
78
+ if (domains.has(domain)) errors.push(`${owner}: ${domain} is already used by ${domains.get(domain)}`)
79
+ else domains.set(domain, owner)
80
+ }
81
+ if (check(isObject(raw.servers) && Object.keys(raw.servers).length > 0, 'servers: at least one server')) {
82
+ for (const [name, server] of Object.entries(raw.servers)) {
83
+ const at = `servers.${name}`
84
+ if (!check(NAME.test(name), `${at}: a name in lowercase letters, digits and dashes`)) continue
85
+ if (!check(isObject(server), `${at}: expected host, email and sites`)) continue
86
+ unknownKeys(server, ['host', 'email', 'sites', 'custom'], `${at}.`, errors)
87
+ check(typeof server.host === 'string' && /^ssh:\/\/[^/]+$/.test(server.host), `${at}.host: ssh://user@host[:port]`)
88
+ check(typeof server.email === 'string' && /^[^@\s]+@[^@\s]+$/.test(server.email), `${at}.email: the Let's Encrypt account`)
89
+ const sites = []
90
+ for (const [siteName, site] of Object.entries(server.sites ?? {})) {
91
+ const siteAt = `${at}.sites.${siteName}`
92
+ if (!check(NAME.test(siteName), `${siteAt}: a name in lowercase letters, digits and dashes`)) continue
93
+ if (siteNames.has(siteName)) {
94
+ errors.push(`${siteAt}: the name is already used on ${siteNames.get(siteName)} (a site name is unique on all the servers)`)
95
+ continue
96
+ }
97
+ siteNames.set(siteName, `servers.${name}`)
98
+ if (!check(isObject(site), `${siteAt}: expected source and domain`)) continue
99
+ unknownKeys(site, ['source', 'domain', 'aliases', 'memory'], `${siteAt}.`, errors)
100
+ const source = typeof site.source === 'string' ? resolve(dir, site.source) : undefined
101
+ let withClient = false
102
+ if (check(source !== undefined, `${siteAt}.source: the folder of the ramdb2 project`)) {
103
+ const pkg = readPackage(join(source, 'package.json'))
104
+ if (check(pkg !== null, `${siteAt}.source: no package.json in ${source}`)) {
105
+ withClient = Array.isArray(pkg.workspaces) && pkg.workspaces.includes('server') && pkg.workspaces.includes('web')
106
+ const lock = existsSync(join(source, 'package-lock.json'))
107
+ check(lock, `${siteAt}.source: no package-lock.json in ${source} (run npm install there)`)
108
+ }
109
+ }
110
+ const aliases = site.aliases ?? []
111
+ if (check(typeof site.domain === 'string' && DOMAIN.test(site.domain), `${siteAt}.domain: a domain name in lowercase`)) {
112
+ claim(site.domain, siteAt)
113
+ }
114
+ if (check(Array.isArray(aliases) && aliases.every(alias => typeof alias === 'string' && DOMAIN.test(alias)),
115
+ `${siteAt}.aliases: a list of domain names in lowercase`)) {
116
+ for (const alias of aliases) claim(alias, siteAt)
117
+ }
118
+ check(site.memory === undefined || (typeof site.memory === 'string' && MEMORY.test(site.memory)),
119
+ `${siteAt}.memory: a size, e.g. 512m or 2g`)
120
+ sites.push({ name: siteName, source, withClient, domain: site.domain, aliases, memory: site.memory })
121
+ }
122
+ const custom = []
123
+ if (check(server.custom === undefined || Array.isArray(server.custom), `${at}.custom: a list`)) {
124
+ for (const [index, entry] of (server.custom ?? []).entries()) {
125
+ const customAt = `${at}.custom[${index}]`
126
+ const item = typeof entry === 'string' ? { name: entry } : entry
127
+ if (!check(isObject(item) && typeof item.name === 'string' && NAME.test(item.name),
128
+ `${customAt}: a name, or { name, domains }`)) continue
129
+ unknownKeys(item, ['name', 'domains'], `${customAt}.`, errors)
130
+ const nginx = join(dir, 'custom', `${item.name}.nginx.conf`)
131
+ const compose = join(dir, 'custom', `${item.name}.compose.yaml`)
132
+ check(existsSync(nginx), `${customAt}: custom/${item.name}.nginx.conf not found`)
133
+ const customDomains = item.domains ?? []
134
+ if (check(Array.isArray(customDomains) && customDomains.every(domain => typeof domain === 'string' && DOMAIN.test(domain)),
135
+ `${customAt}.domains: a list of domain names in lowercase`)) {
136
+ for (const domain of customDomains) claim(domain, customAt)
137
+ }
138
+ custom.push({ name: item.name, nginx, compose: existsSync(compose) ? compose : undefined, domains: customDomains })
139
+ }
140
+ }
141
+ check(sites.length + custom.length > 0, `${at}: no site`)
142
+ servers.push({ name, host: server.host, email: server.email, sites, custom })
143
+ }
144
+ }
145
+ if (errors.length > 0) throw new InfraError(errors)
146
+ return { dir, backup, servers }
147
+ }
148
+
149
+ function isObject(value) {
150
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
151
+ }
152
+
153
+ function unknownKeys(object, known, at, errors) {
154
+ for (const key of Object.keys(object)) {
155
+ if (!known.includes(key)) errors.push(`${at}${key}: unknown key (expected ${known.join(', ')})`)
156
+ }
157
+ }
158
+
159
+ function readPackage(file) {
160
+ try {
161
+ return JSON.parse(readFileSync(file, 'utf8'))
162
+ } catch {
163
+ return null
164
+ }
165
+ }
package/src/model.js ADDED
@@ -0,0 +1,420 @@
1
+ import {
2
+ buildASTSchema, getDirectiveValues, getNamedType, isEnumType, isLeafType, isListType, isNonNullType, isObjectType,
3
+ isScalarType, Kind, parse, specifiedScalarTypes, visit,
4
+ } from 'graphql'
5
+ import { DIRECTIVES } from './directives.js'
6
+
7
+ // Reads a preTypeDefs into the model the generators use, and checks it (spec section 3).
8
+ // Every error is collected: the generation stops on a SchemaError that lists them all.
9
+
10
+ const BUILT_IN = { Int: 'number', Float: 'number', String: 'string', ID: 'string', Boolean: 'boolean' }
11
+ const DEFAULTS = { Int: '0', Float: '0', String: "''", ID: "''", Boolean: 'false' }
12
+
13
+ /**
14
+ * Thrown when the schema is invalid. `errors` lists every problem found.
15
+ */
16
+ export class SchemaError extends Error {
17
+ name = 'SchemaError'
18
+
19
+ /** @param {string[]} errors */
20
+ constructor(errors) {
21
+ super('Invalid schema:\n' + errors.map(error => ' - ' + error).join('\n'))
22
+ this.errors = errors
23
+ }
24
+ }
25
+
26
+ /**
27
+ * @typedef {object} Field a persistent scalar, enum or custom scalar field
28
+ * @property {string} name
29
+ * @property {string} gqlType named GraphQL type
30
+ * @property {boolean} nonNull
31
+ * @property {string} jsType for the JSDoc
32
+ * @property {string} defaultValue JavaScript code
33
+ * @property {string | undefined} description
34
+ * @property {{regex: string, message?: string} | undefined} pattern
35
+ * @property {string[] | undefined} enumValues
36
+ * @property {boolean} sensitive @sensitive: masked in the logs
37
+ * @property {boolean} private @private: absent from the GraphQL API
38
+ *
39
+ * @typedef {object} Parent an object relation: this type holds the foreign key
40
+ * @property {string} name relation, e.g. project
41
+ * @property {string} fk foreign key, e.g. idProject
42
+ * @property {string} target type name
43
+ * @property {boolean} required
44
+ * @property {string | undefined} description
45
+ *
46
+ * @typedef {object} Child a list relation: the other type holds the foreign key
47
+ * @property {string} name relation, e.g. taskRoles
48
+ * @property {string} fk foreign key in the target type
49
+ * @property {string} target type name
50
+ * @property {string | undefined} onDelete explicit @onDelete
51
+ * @property {string | undefined} description
52
+ *
53
+ * @typedef {object} Computed
54
+ * @property {string} name
55
+ * @property {string[]} depends
56
+ * @property {string} jsType
57
+ * @property {string} display GraphQL type, e.g. Float!
58
+ * @property {string | undefined} description
59
+ *
60
+ * @typedef {object} Transient a @transient field: resolved by the project, not stored
61
+ * @property {string} name
62
+ * @property {string} display GraphQL type, e.g. String!
63
+ * @property {string} jsType
64
+ * @property {string | undefined} description
65
+ * @property {boolean} scalar scalar, enum, custom scalar or a list of them (a type of another layer is a scalar)
66
+ * @property {string[]} requiredArgs arguments without a default value
67
+ *
68
+ * @typedef {object} Index
69
+ * @property {string} name
70
+ * @property {string[]} fields
71
+ * @property {'map' | 'btree' | 'fulltext'} type
72
+ * @property {boolean} [unique] MAP only: no two objects with the same values
73
+ *
74
+ * @typedef {object} Type a persistent type: one ramdb2 table
75
+ * @property {string} name
76
+ * @property {string} table
77
+ * @property {string | undefined} description
78
+ * @property {string | undefined} group
79
+ * @property {Field[]} fields without id
80
+ * @property {Parent[]} parents
81
+ * @property {Child[]} children
82
+ * @property {Computed[]} computed
83
+ * @property {Transient[]} transient fields resolved by the project on the server
84
+ * @property {Index[]} indexes declared with @index (the inverse indexes of the foreign keys are automatic)
85
+ *
86
+ * @typedef {object} Model
87
+ * @property {Type[]} types
88
+ * @property {Map<string, Type>} byName
89
+ * @property {import('graphql').DocumentNode} document the preTypeDefs, without the directive declarations
90
+ * @property {string[]} warnings
91
+ */
92
+
93
+ /**
94
+ * @param {string} source the preTypeDefs (one or several files concatenated)
95
+ * @returns {Model}
96
+ */
97
+ export function readSchema(source) {
98
+ let document
99
+ let schema
100
+ const warnings = []
101
+ try {
102
+ document = parse(source)
103
+ // Types defined elsewhere (by the server layer, or in a file not given) become placeholder scalars
104
+ const missing = undefinedTypes(document)
105
+ for (const name of missing) warnings.push(`${name} is not defined in the schema: read as a scalar`)
106
+ const placeholders = missing.map(name => `scalar ${name}`).join('\n')
107
+ schema = buildASTSchema(parse(DIRECTIVES + '\n' + placeholders + '\n' + source))
108
+ } catch (error) {
109
+ throw new SchemaError([error.message])
110
+ }
111
+ const errors = []
112
+ const directive = name => schema.getDirective(name)
113
+ // buildASTSchema does not check the values of the directive arguments: getDirectiveValues does
114
+ const values = (name, node) => {
115
+ try {
116
+ return getDirectiveValues(directive(name), node) ?? undefined
117
+ } catch (error) {
118
+ errors.push(`${node.name.value}: @${name}: ${error.message}`)
119
+ return undefined
120
+ }
121
+ }
122
+
123
+ const types = []
124
+ const byName = new Map()
125
+ for (const gqlType of Object.values(schema.getTypeMap())) {
126
+ if (!isObjectType(gqlType) || gqlType.astNode === undefined) continue
127
+ if (values('persistent', gqlType.astNode) === undefined) continue
128
+ const type = {
129
+ name: gqlType.name,
130
+ table: lowerFirst(gqlType.name),
131
+ description: gqlType.description ?? undefined,
132
+ group: values('group', gqlType.astNode)?.name,
133
+ fields: [],
134
+ parents: [],
135
+ children: [],
136
+ computed: [],
137
+ transient: [],
138
+ indexes: [],
139
+ _gql: gqlType,
140
+ }
141
+ types.push(type)
142
+ byName.set(type.name, type)
143
+ }
144
+
145
+ const isPersistent = gqlType => byName.has(gqlType.name)
146
+
147
+ // Fields and relations
148
+ for (const type of types) {
149
+ const at = field => `${type.name}.${field}`
150
+ for (const gqlField of Object.values(type._gql.getFields())) {
151
+ const node = gqlField.astNode
152
+ const name = gqlField.name
153
+ const named = getNamedType(gqlField.type)
154
+ const nonNull = isNonNullType(gqlField.type)
155
+ const list = isListType(isNonNullType(gqlField.type) ? gqlField.type.ofType : gqlField.type)
156
+ const description = gqlField.description ?? undefined
157
+ const computed = values('computed', node)
158
+ const transient = values('transient', node) !== undefined
159
+ const pattern = values('pattern', node)
160
+ const onDelete = values('onDelete', node)
161
+ const field = values('field', node)
162
+ const isPrivate = values('private', node) !== undefined
163
+ if (isPrivate && (computed !== undefined || transient || name === 'id' || isObjectType(named) || list)) {
164
+ errors.push(`${at(name)}: @private only goes on a stored scalar field`)
165
+ }
166
+
167
+ if (computed !== undefined && transient) errors.push(`${at(name)}: @computed and @transient exclude each other`)
168
+ if (computed !== undefined) {
169
+ type.computed.push({ name, depends: computed.depends, jsType: jsType(gqlField.type, byName), display: String(gqlField.type), description })
170
+ continue
171
+ }
172
+ if (transient) {
173
+ type.transient.push({
174
+ name,
175
+ display: String(gqlField.type),
176
+ jsType: jsType(gqlField.type, byName),
177
+ description,
178
+ scalar: isLeafType(named),
179
+ requiredArgs: gqlField.args.filter(arg => isNonNullType(arg.type) && arg.defaultValue === undefined).map(arg => arg.name),
180
+ })
181
+ continue
182
+ }
183
+ if (name === 'id') {
184
+ if (named.name !== 'Int' || list) errors.push(`${at('id')} must be an Int`)
185
+ continue
186
+ }
187
+
188
+ if (isObjectType(named)) {
189
+ if (!isPersistent(named)) {
190
+ errors.push(`${at(name)}: ${named.name} is not @persistent: add @transient or @computed`)
191
+ } else if (list) {
192
+ if (field === undefined) errors.push(`${at(name)}: a list relation needs @field(name:)`)
193
+ else type.children.push({ name, fk: field.name, target: named.name, onDelete: onDelete?.action, description })
194
+ } else {
195
+ type.parents.push({ name, fk: 'id' + upperFirst(name), target: named.name, required: nonNull, description })
196
+ }
197
+ if (field !== undefined && !list) errors.push(`${at(name)}: @field only goes on a list relation`)
198
+ if (onDelete !== undefined && !list) errors.push(`${at(name)}: @onDelete only goes on a list relation`)
199
+ if (pattern !== undefined) errors.push(`${at(name)}: @pattern only goes on a scalar field`)
200
+ continue
201
+ }
202
+ if (list) {
203
+ errors.push(`${at(name)}: a list of scalars cannot be persistent: add @transient or @computed`)
204
+ continue
205
+ }
206
+ for (const [directiveName, value] of [['field', field], ['onDelete', onDelete]]) {
207
+ if (value !== undefined) errors.push(`${at(name)}: @${directiveName} only goes on a list relation`)
208
+ }
209
+ if (pattern !== undefined) {
210
+ try {
211
+ new RegExp(pattern.regex)
212
+ } catch (error) {
213
+ errors.push(`${at(name)}: invalid @pattern regex: ${error.message}`)
214
+ }
215
+ }
216
+ const enumValues = isEnumType(named) ? named.getValues().map(value => value.name) : undefined
217
+ // A required private field: the API could never create the object
218
+ if (isPrivate && nonNull && (named.name === 'String' || named.name === 'ID' || defaultValue(named, nonNull) === 'null')) {
219
+ errors.push(`${at(name)}: a @private field cannot be required (no "!"): the API could not create the object`)
220
+ }
221
+ type.fields.push({
222
+ name,
223
+ gqlType: named.name,
224
+ nonNull,
225
+ jsType: jsType(gqlField.type, byName),
226
+ defaultValue: defaultValue(named, nonNull),
227
+ description,
228
+ pattern,
229
+ enumValues,
230
+ sensitive: values('sensitive', node) !== undefined,
231
+ private: isPrivate,
232
+ })
233
+ }
234
+ }
235
+
236
+ checkRelations(types, byName, errors)
237
+ for (const type of types) readIndexes(type, values, errors)
238
+ for (const type of types) checkComputed(type, byName, errors)
239
+
240
+ if (errors.length > 0) throw new SchemaError(errors)
241
+ for (const type of types) delete type._gql
242
+ return { types, byName, document, warnings }
243
+ }
244
+
245
+ function undefinedTypes(document) {
246
+ const defined = new Set([...specifiedScalarTypes.map(type => type.name), 'RamdbIndexType', 'RamdbOnDelete'])
247
+ for (const definition of document.definitions) {
248
+ if (definition.name !== undefined && !definition.kind.endsWith('Extension')) defined.add(definition.name.value)
249
+ }
250
+ const missing = new Set()
251
+ visit(document, {
252
+ NamedType(node) {
253
+ if (!defined.has(node.name.value)) missing.add(node.name.value)
254
+ },
255
+ })
256
+ return [...missing]
257
+ }
258
+
259
+ // Every list relation must match an object relation of the other type pointing back here
260
+ function checkRelations(types, byName, errors) {
261
+ for (const type of types) {
262
+ const names = new Set()
263
+ for (const name of [...type.fields.map(f => f.name), ...type.parents.map(p => p.fk)]) {
264
+ if (names.has(name)) errors.push(`${type.name}.${name} is declared twice (an object relation adds its foreign key)`)
265
+ names.add(name)
266
+ }
267
+ for (const child of type.children) {
268
+ const parent = byName.get(child.target).parents.find(p => p.fk === child.fk)
269
+ if (parent === undefined || parent.target !== type.name) {
270
+ errors.push(`${type.name}.${child.name}: @field(name: "${child.fk}") needs an object relation ` +
271
+ `${lowerFirst(child.fk.slice(2))}: ${type.name} in ${child.target}`)
272
+ }
273
+ }
274
+ }
275
+ }
276
+
277
+ function readIndexes(type, values, errors) {
278
+ const add = (index, where) => {
279
+ if (type.indexes.some(other => other.name === index.name)) {
280
+ errors.push(`${where}: two indexes are named ${index.name}: give one a name:`)
281
+ }
282
+ type.indexes.push(index)
283
+ }
284
+ const fullText = []
285
+ const node = type._gql.astNode
286
+ // A repeatable directive: getDirectiveValues reads only the first one
287
+ for (const directiveNode of node.directives.filter(d => d.name.value === 'index')) {
288
+ const args = argumentsOf(directiveNode)
289
+ if (args.fields === undefined || args.fields.length < 2) {
290
+ errors.push(`${type.name}: @index on a type needs fields: [...] with at least two fields`)
291
+ continue
292
+ }
293
+ if ((args.type ?? 'MAP') !== 'MAP') errors.push(`${type.name}: @index on a type is a MAP index`)
294
+ const unique = args.unique === true
295
+ for (const field of args.fields) {
296
+ if (field !== 'id' && !type.fields.some(f => f.name === field) && !type.parents.some(p => p.fk === field)) {
297
+ errors.push(`${type.name}: @index(fields:) names the unknown field ${field}`)
298
+ }
299
+ }
300
+ add({ name: args.name ?? args.fields.join('_'), fields: args.fields, type: 'map', ...(unique && { unique }) }, type.name)
301
+ }
302
+ for (const gqlField of Object.values(type._gql.getFields())) {
303
+ for (const directiveNode of gqlField.astNode.directives.filter(d => d.name.value === 'index')) {
304
+ const args = argumentsOf(directiveNode)
305
+ const where = `${type.name}.${gqlField.name}`
306
+ if (args.fields !== undefined) errors.push(`${where}: fields: only goes on an @index of a type`)
307
+ if (!type.fields.some(f => f.name === gqlField.name)) {
308
+ errors.push(`${where}: @index only goes on a persistent scalar field`)
309
+ continue
310
+ }
311
+ const kind = (args.type ?? 'MAP').toLowerCase()
312
+ const unique = args.unique === true
313
+ if (unique && kind !== 'map') errors.push(`${where}: only a MAP index can be unique`)
314
+ // $text searches every full-text field: a private one could be found by its content
315
+ if (kind === 'fulltext' && type.fields.find(f => f.name === gqlField.name).private) {
316
+ errors.push(`${where}: a @private field cannot have a FULLTEXT index`)
317
+ }
318
+ if (kind === 'fulltext') fullText.push(gqlField.name)
319
+ else add({ name: args.name ?? gqlField.name, fields: [gqlField.name], type: kind, ...(unique && { unique }) }, where)
320
+ }
321
+ }
322
+ // One full-text index per table, over all its FULLTEXT fields (D21)
323
+ if (fullText.length > 0) add({ name: 'fullText', fields: fullText, type: 'fulltext' }, type.name)
324
+ }
325
+
326
+ function argumentsOf(directiveNode) {
327
+ const args = {}
328
+ for (const argument of directiveNode.arguments) {
329
+ const value = argument.value
330
+ args[argument.name.value] = value.kind === 'ListValue' ? value.values.map(v => v.value) : value.value
331
+ }
332
+ return args
333
+ }
334
+
335
+ // Each path goes through relations and ends on a persistent field, a foreign key, a relation or a computed field.
336
+ // Only cycles on the same object are refused: through a relation, a tree is fine (D12).
337
+ function checkComputed(type, byName, errors) {
338
+ for (const computed of type.computed) {
339
+ for (const path of computed.depends) {
340
+ const problem = resolvePath(type, path.split('.'), byName).error
341
+ if (problem !== undefined) errors.push(`${type.name}.${computed.name}: depends "${path}": ${problem}`)
342
+ }
343
+ }
344
+ const local = new Map(type.computed.map(c => [c.name, c.depends.filter(path => !path.includes('.'))]))
345
+ const visiting = new Set()
346
+ const done = new Set()
347
+ const visit = (name, chain) => {
348
+ if (done.has(name)) return
349
+ if (visiting.has(name)) {
350
+ errors.push(`${type.name}: computed fields depend on each other in a cycle: ${[...chain, name].join(' -> ')}`)
351
+ return
352
+ }
353
+ visiting.add(name)
354
+ for (const next of local.get(name) ?? []) if (local.has(next)) visit(next, [...chain, name])
355
+ visiting.delete(name)
356
+ done.add(name)
357
+ }
358
+ for (const name of local.keys()) visit(name, [])
359
+ }
360
+
361
+ /**
362
+ * Follows a dependency path from a type.
363
+ * @returns {{steps?: {relation: Parent | Child, kind: 'parent' | 'child', from: Type, to: Type}[], end?: Type, last?: string, error?: string}}
364
+ */
365
+ export function resolvePath(type, segments, byName) {
366
+ const steps = []
367
+ let current = type
368
+ for (let i = 0; i < segments.length; i++) {
369
+ const segment = segments[i]
370
+ const isLast = i === segments.length - 1
371
+ const parent = current.parents.find(p => p.name === segment)
372
+ const child = current.children.find(c => c.name === segment)
373
+ if (parent !== undefined || child !== undefined) {
374
+ const relation = parent ?? child
375
+ const to = byName.get(relation.target)
376
+ steps.push({ relation, kind: parent !== undefined ? 'parent' : 'child', from: current, to })
377
+ current = to
378
+ if (isLast) return { steps, end: current, last: undefined }
379
+ continue
380
+ }
381
+ if (!isLast) return { error: `${segment} is not a relation of ${current.name}` }
382
+ const known = segment === 'id' || current.fields.some(f => f.name === segment) ||
383
+ current.parents.some(p => p.fk === segment) || current.computed.some(c => c.name === segment)
384
+ if (!known) return { error: `${segment} is not a field of ${current.name}` }
385
+ return { steps, end: current, last: segment }
386
+ }
387
+ return { error: 'empty path' }
388
+ }
389
+
390
+ function jsType(gqlType, byName) {
391
+ const nonNull = isNonNullType(gqlType)
392
+ const inner = nonNull ? gqlType.ofType : gqlType
393
+ if (isListType(inner)) {
394
+ const item = jsType(inner.ofType, byName)
395
+ return `${item.includes(' | ') ? `(${item})` : item}[]${nonNull ? '' : ' | null'}`
396
+ }
397
+ const named = getNamedType(inner)
398
+ let base
399
+ if (BUILT_IN[named.name] !== undefined) base = BUILT_IN[named.name]
400
+ else if (isEnumType(named)) base = named.getValues().map(v => `'${v.name}'`).join(' | ')
401
+ else if (isObjectType(named)) base = byName.has(named.name) ? named.name : 'object'
402
+ else base = 'any'
403
+ return nonNull ? base : `${base} | null`
404
+ }
405
+
406
+ // Same defaults as the v1 whatever the nullability; an enum starts on its first value
407
+ function defaultValue(named, nonNull) {
408
+ if (DEFAULTS[named.name] !== undefined) return DEFAULTS[named.name]
409
+ if (isEnumType(named)) return nonNull ? `'${named.getValues()[0].name}'` : 'null'
410
+ if (isScalarType(named)) return 'null'
411
+ return 'null'
412
+ }
413
+
414
+ export function lowerFirst(string) {
415
+ return string.charAt(0).toLowerCase() + string.slice(1)
416
+ }
417
+
418
+ export function upperFirst(string) {
419
+ return string.charAt(0).toUpperCase() + string.slice(1)
420
+ }