@contember/binding 1.0.0 → 1.1.0-alpha.0

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 (114) hide show
  1. package/dist/development/core/DataBinding.js +18 -17
  2. package/dist/development/core/DataBinding.js.map +1 -1
  3. package/dist/development/core/MarkerComparator.js +1 -1
  4. package/dist/development/core/MarkerMerger.js +1 -4
  5. package/dist/development/core/MarkerMerger.js.map +1 -1
  6. package/dist/development/core/StateInitializer.js +1 -3
  7. package/dist/development/core/StateInitializer.js.map +1 -1
  8. package/dist/development/core/VariableInputTransformer.js +4 -1
  9. package/dist/development/core/VariableInputTransformer.js.map +1 -1
  10. package/dist/development/core/operations/EntityOperations.js +1 -1
  11. package/dist/development/core/schema/Schema.js +3 -0
  12. package/dist/development/core/schema/Schema.js.map +1 -1
  13. package/dist/development/coreComponents/EntityListSubTree.js +4 -12
  14. package/dist/development/coreComponents/EntityListSubTree.js.map +1 -1
  15. package/dist/development/coreComponents/EntitySubTree.js +4 -22
  16. package/dist/development/coreComponents/EntitySubTree.js.map +1 -1
  17. package/dist/development/coreComponents/Field.js +5 -1
  18. package/dist/development/coreComponents/Field.js.map +1 -1
  19. package/dist/development/coreComponents/HasMany.js +3 -5
  20. package/dist/development/coreComponents/HasMany.js.map +1 -1
  21. package/dist/development/coreComponents/HasOne.js +3 -5
  22. package/dist/development/coreComponents/HasOne.js.map +1 -1
  23. package/dist/development/dao/Environment.js +147 -94
  24. package/dist/development/dao/Environment.js.map +1 -1
  25. package/dist/development/dao/TreeNodeEnvironmentFactory.js +159 -0
  26. package/dist/development/dao/TreeNodeEnvironmentFactory.js.map +1 -0
  27. package/dist/development/queryLanguage/MarkerFactory.js +4 -3
  28. package/dist/development/queryLanguage/MarkerFactory.js.map +1 -1
  29. package/dist/development/queryLanguage/Parser.js +18 -6
  30. package/dist/development/queryLanguage/Parser.js.map +1 -1
  31. package/dist/production/core/DataBinding.js +18 -8
  32. package/dist/production/core/DataBinding.js.map +1 -1
  33. package/dist/production/core/MarkerComparator.js +1 -1
  34. package/dist/production/core/MarkerMerger.js +1 -4
  35. package/dist/production/core/MarkerMerger.js.map +1 -1
  36. package/dist/production/core/StateInitializer.js +1 -3
  37. package/dist/production/core/StateInitializer.js.map +1 -1
  38. package/dist/production/core/VariableInputTransformer.js +4 -1
  39. package/dist/production/core/VariableInputTransformer.js.map +1 -1
  40. package/dist/production/core/operations/EntityOperations.js +1 -1
  41. package/dist/production/core/schema/Schema.js +3 -0
  42. package/dist/production/core/schema/Schema.js.map +1 -1
  43. package/dist/production/coreComponents/EntityListSubTree.js +4 -12
  44. package/dist/production/coreComponents/EntityListSubTree.js.map +1 -1
  45. package/dist/production/coreComponents/EntitySubTree.js +4 -22
  46. package/dist/production/coreComponents/EntitySubTree.js.map +1 -1
  47. package/dist/production/coreComponents/Field.js +5 -1
  48. package/dist/production/coreComponents/Field.js.map +1 -1
  49. package/dist/production/coreComponents/HasMany.js +3 -5
  50. package/dist/production/coreComponents/HasMany.js.map +1 -1
  51. package/dist/production/coreComponents/HasOne.js +3 -5
  52. package/dist/production/coreComponents/HasOne.js.map +1 -1
  53. package/dist/production/dao/Environment.js +147 -94
  54. package/dist/production/dao/Environment.js.map +1 -1
  55. package/dist/production/dao/TreeNodeEnvironmentFactory.js +159 -0
  56. package/dist/production/dao/TreeNodeEnvironmentFactory.js.map +1 -0
  57. package/dist/production/queryLanguage/MarkerFactory.js +4 -3
  58. package/dist/production/queryLanguage/MarkerFactory.js.map +1 -1
  59. package/dist/production/queryLanguage/Parser.js +15 -6
  60. package/dist/production/queryLanguage/Parser.js.map +1 -1
  61. package/dist/types/accessorTree/MutationRequestResponse.d.ts +4 -0
  62. package/dist/types/accessorTree/MutationRequestResponse.d.ts.map +1 -1
  63. package/dist/types/accessorTree/QueryRequestResponse.d.ts +4 -0
  64. package/dist/types/accessorTree/QueryRequestResponse.d.ts.map +1 -1
  65. package/dist/types/accessorTree/RequestError.d.ts +9 -1
  66. package/dist/types/accessorTree/RequestError.d.ts.map +1 -1
  67. package/dist/types/core/DataBinding.d.ts.map +1 -1
  68. package/dist/types/core/MarkerMerger.d.ts.map +1 -1
  69. package/dist/types/core/StateInitializer.d.ts.map +1 -1
  70. package/dist/types/core/VariableInputTransformer.d.ts.map +1 -1
  71. package/dist/types/core/schema/Schema.d.ts +2 -0
  72. package/dist/types/core/schema/Schema.d.ts.map +1 -1
  73. package/dist/types/core/schema/index.d.ts +0 -1
  74. package/dist/types/core/schema/index.d.ts.map +1 -1
  75. package/dist/types/coreComponents/EntityListSubTree.d.ts +1 -1
  76. package/dist/types/coreComponents/EntityListSubTree.d.ts.map +1 -1
  77. package/dist/types/coreComponents/EntitySubTree.d.ts +1 -1
  78. package/dist/types/coreComponents/EntitySubTree.d.ts.map +1 -1
  79. package/dist/types/coreComponents/Field.d.ts.map +1 -1
  80. package/dist/types/coreComponents/HasMany.d.ts +1 -1
  81. package/dist/types/coreComponents/HasMany.d.ts.map +1 -1
  82. package/dist/types/coreComponents/HasOne.d.ts +1 -1
  83. package/dist/types/coreComponents/HasOne.d.ts.map +1 -1
  84. package/dist/types/dao/Environment.d.ts +82 -43
  85. package/dist/types/dao/Environment.d.ts.map +1 -1
  86. package/dist/types/dao/TreeNodeEnvironmentFactory.d.ts +19 -0
  87. package/dist/types/dao/TreeNodeEnvironmentFactory.d.ts.map +1 -0
  88. package/dist/types/queryLanguage/MarkerFactory.d.ts.map +1 -1
  89. package/dist/types/queryLanguage/Parser.d.ts.map +1 -1
  90. package/dist/types/tsconfig.tsbuildinfo +1 -1
  91. package/package.json +9 -6
  92. package/src/accessorTree/MutationRequestResponse.ts +1 -0
  93. package/src/accessorTree/QueryRequestResponse.ts +1 -0
  94. package/src/accessorTree/RequestError.ts +7 -1
  95. package/src/core/DataBinding.ts +23 -26
  96. package/src/core/MarkerMerger.ts +1 -4
  97. package/src/core/StateInitializer.ts +1 -3
  98. package/src/core/VariableInputTransformer.ts +7 -4
  99. package/src/core/schema/Schema.ts +5 -0
  100. package/src/core/schema/index.ts +0 -1
  101. package/src/coreComponents/EntityListSubTree.tsx +5 -16
  102. package/src/coreComponents/EntitySubTree.tsx +17 -32
  103. package/src/coreComponents/Field.tsx +4 -0
  104. package/src/coreComponents/HasMany.tsx +4 -6
  105. package/src/coreComponents/HasOne.tsx +6 -7
  106. package/src/dao/Environment.ts +221 -126
  107. package/src/dao/TreeNodeEnvironmentFactory.ts +228 -0
  108. package/src/queryLanguage/MarkerFactory.ts +5 -3
  109. package/src/queryLanguage/Parser.ts +24 -11
  110. package/dist/development/core/schema/SchemaValidator.js +0 -116
  111. package/dist/development/core/schema/SchemaValidator.js.map +0 -1
  112. package/dist/types/core/schema/SchemaValidator.d.ts +0 -14
  113. package/dist/types/core/schema/SchemaValidator.d.ts.map +0 -1
  114. package/src/core/schema/SchemaValidator.ts +0 -238
@@ -1,201 +1,296 @@
1
1
  import type { ReactNode } from 'react'
2
- import type { Filter, UniqueWhere } from '../treeParameters'
2
+ import { BindingError } from '../BindingError'
3
+ import type { Filter } from '../treeParameters'
4
+ import equal from 'fast-deep-equal/es6'
5
+ import { Schema, SchemaColumn, SchemaEntity, SchemaRelation } from '../core/schema'
3
6
 
4
7
  class Environment {
5
- private readonly names: Environment.NameStore
6
-
7
- public constructor(names: Environment.NameStore = Environment.defaultNameStore) {
8
- this.names = {
9
- ...Environment.defaultNameStore,
10
- ...names,
11
- }
8
+ private constructor(
9
+ private readonly options: Environment.Options,
10
+ ) {
12
11
  }
13
12
 
14
- public static create(delta: Partial<Environment.NameStore> = {}) {
13
+ public static create() {
15
14
  return new Environment({
16
- ...Environment.defaultSystemVariables,
17
15
  dimensions: {},
18
- }).putDelta(delta)
16
+ variables: {},
17
+ parameters: {},
18
+ })
19
19
  }
20
20
 
21
- public hasName(name: keyof Environment.NameStore): boolean {
22
- return name in this.names
21
+ public getSubTree(): Environment.SubTreeNode {
22
+ for (let env: Environment = this; env.options.node; env = env.getParent()) {
23
+ const node = env.options.node
24
+ if (node.type === 'subtree-entity' || node.type === 'subtree-entity-list') {
25
+ return node
26
+ }
27
+ }
28
+ throw new BindingError('Not in a SubTree')
23
29
  }
24
30
 
25
- public hasDimension(dimensionName: keyof Environment.SelectedDimensions): boolean {
26
- return dimensionName in this.names.dimensions
31
+ public getSubTreeNode(): Environment.AnyNode {
32
+ if (!this.options.node) {
33
+ throw new BindingError()
34
+ }
35
+ return this.options.node
27
36
  }
28
37
 
29
- public getValueOrElse<F, V extends Environment.Value = Environment.Value>(
30
- name: keyof Environment.NameStore,
31
- fallback: F,
32
- ): V | F {
33
- if (!this.hasName(name)) {
34
- return fallback
35
- }
36
- return this.names[name] as V
38
+ public withSubTree(SubTree: Environment.SubTreeNode) {
39
+ const { parent, ...options } = this.options
40
+ return new Environment({
41
+ ...options,
42
+ node: SubTree,
43
+ })
37
44
  }
38
45
 
39
- public getDimensionOrElse<F>(dimensionName: keyof Environment.SelectedDimensions, fallback: F): string[] | F {
40
- if (!this.hasDimension(dimensionName)) {
41
- return fallback
46
+ public withSubTreeChild(node: Environment.InnerNode) {
47
+ if (!this.options.node) {
48
+ throw new BindingError(`Cannot call withSubTreeChild without previous call of withSubTree`)
42
49
  }
43
- return this.names.dimensions[dimensionName]
50
+ if (this.options.node.entity.fields.get(node.field.name) !== node.field) {
51
+ throw new BindingError()
52
+ }
53
+ return new Environment({
54
+ ...this.options,
55
+ node,
56
+ parent: this,
57
+ })
44
58
  }
45
59
 
46
- public getValue<V extends Environment.Value = Environment.Value>(name: keyof Environment.NameStore): V {
47
- return this.names[name] as V
48
- }
49
60
 
50
- public getDimension(dimensionName: keyof Environment.SelectedDimensions): string[] {
51
- return this.names.dimensions[dimensionName]
61
+ public hasVariable(key: string): boolean {
62
+ return key in this.options.variables
52
63
  }
53
64
 
54
- public getAllNames(): Environment.NameStore {
55
- return { ...this.names }
65
+ public getVariable<V extends Environment.Value = Environment.Value>(key: string): V {
66
+ if (!(key in this.options.variables)) {
67
+ throw new BindingError(`Variable ${key} not found`)
68
+ }
69
+ return this.options.variables[key] as V
56
70
  }
57
71
 
58
- public getAllDimensions(): Environment.SelectedDimensions {
59
- return { ...this.names.dimensions }
72
+ public getVariableOrElse<F, V extends Environment.Value = Environment.Value>(key: string, fallback: F): V | F {
73
+ return (this.options.variables[key] as V) ?? fallback
60
74
  }
61
75
 
62
- public getSystemVariable<N extends Environment.SystemVariableName>(name: N): Environment.SystemVariables[N] {
63
- return this.names[name]
76
+ /** @deprecated use getVariable or getParameter */
77
+ public getValue<V extends Environment.Value = Environment.Value>(key: string): V {
78
+ console.warn('Environment.getValue() is deprecated, use Environment.getVariable() or Environment.getParameter() instead.')
79
+ return this.getVariableOrElse(key, undefined) ?? this.getParameterOrElse(key, undefined) as V
64
80
  }
65
81
 
66
- public putName(name: Environment.Name, value: Environment.Value): Environment {
67
- return new Environment({
68
- ...this.names,
69
- dimensions: { ...this.names.dimensions },
70
- [name]: value,
71
- })
82
+ /** @deprecated use getVariableOrElse or getParameterOrElse */
83
+ public getValueOrElse<F, V extends Environment.Value = Environment.Value>(key: string, fallback: F): V | F {
84
+ console.warn('Environment.getValueOrElse() is deprecated, use Environment.getVariableOrElse() or Environment.getParameterOrElse() instead.')
85
+ return this.getVariableOrElse(key, undefined) ?? this.getParameterOrElse(key, fallback) as V | F
72
86
  }
73
87
 
74
- public putSystemVariable<N extends Environment.SystemVariableName>(
75
- name: N,
76
- value: Environment.SystemVariables[N],
77
- ): Environment {
78
- return this.putName(name, value)
88
+ /** @deprecated */
89
+ public hasName(key: string): boolean {
90
+ console.warn('Environment.hasName() is deprecated, use Environment.hasVariable() or Environment.hasParameter() instead.')
91
+ return key in this.options.variables || key in this.options.parameters
79
92
  }
80
93
 
81
- public putDelta(delta: Partial<Environment.NameStore>): Environment {
82
- const currentNames = this.getAllNames()
83
-
84
- for (const newName in delta) {
85
- const deltaValue = delta[newName]
86
- if (deltaValue === undefined) {
87
- delete currentNames[newName]
94
+ public withVariables(variables: Environment.ValuesMapWithFactory | undefined): Environment {
95
+ if (variables === undefined) {
96
+ return this
97
+ }
98
+ const newVariables = { ...this.options.variables }
99
+ for (const [newName, newValue] of Object.entries(variables)) {
100
+ if (newName === 'labelMiddleware') {
101
+ throw new BindingError('You cannot pass labelMiddleware to withVariables method. Use withLabelMiddleware instead.')
102
+ }
103
+ const resolvedValue = typeof newValue === 'function' ? newValue(this) : newValue
104
+ if (resolvedValue === undefined) {
105
+ delete newVariables[newName]
88
106
  } else {
89
- currentNames[newName] = deltaValue
107
+ newVariables[newName] = resolvedValue
90
108
  }
91
109
  }
110
+ return new Environment({ ...this.options, variables: newVariables })
111
+ }
92
112
 
93
- return new Environment(currentNames)
113
+ public hasParameter(key: string): boolean {
114
+ return key in this.options.parameters
94
115
  }
95
116
 
96
- public updateDimensionsIfNecessary(
97
- dimensions: Environment.NameStore['dimensions'],
98
- defaultDimensions: Environment.NameStore['dimensions'],
99
- ): Environment {
100
- const normalizedDimensions: Environment.NameStore['dimensions'] = {
101
- ...defaultDimensions,
102
- ...dimensions,
117
+ public getParameter<F>(key: string): string {
118
+ if (!(key in this.options.parameters) || this.options.parameters[key] === undefined) {
119
+ throw new BindingError(`Parameter ${key} not found`)
103
120
  }
121
+ return this.options.parameters[key] as string
122
+ }
104
123
 
105
- const dimensionsEqual = JSON.stringify(this.names.dimensions) === JSON.stringify(normalizedDimensions)
106
- return dimensionsEqual
107
- ? this
108
- : new Environment({
109
- ...this.names,
110
- dimensions: { ...normalizedDimensions },
111
- })
124
+ public getParameterOrElse<F>(key: string, fallback: F): string | F {
125
+ return this.options.parameters[key] ?? fallback
112
126
  }
113
127
 
114
- public static generateDelta(
115
- currentEnvironment: Environment,
116
- delta: Environment.DeltaFactory,
117
- ): Partial<Environment.NameStore> {
118
- const newDelta: Partial<Environment.NameStore> = {}
119
128
 
120
- for (const name in delta) {
121
- const value = delta[name]
129
+ public withParameters(parameters: Environment.Parameters): Environment {
130
+ return new Environment({ ...this.options, parameters })
131
+ }
132
+
133
+ public hasDimension(dimensionName: string): boolean {
134
+ return dimensionName in this.options.dimensions
135
+ }
122
136
 
123
- newDelta[name] =
124
- value &&
125
- value instanceof Function &&
126
- !Environment.systemVariableNames.has(name as Environment.SystemVariableName)
127
- ? value(currentEnvironment)
128
- : delta[name]
137
+ public getDimension<F>(dimensionName: string): string[] {
138
+ if (!(dimensionName in this.options.dimensions)) {
139
+ throw new BindingError(`Dimension ${dimensionName} does not exist.`)
129
140
  }
141
+ return this.options.dimensions[dimensionName]
142
+ }
143
+
144
+ public getDimensionOrElse<F>(dimensionName: string, fallback: F): string[] | F {
145
+ return this.options.dimensions[dimensionName] ?? fallback
146
+ }
130
147
 
131
- return newDelta
148
+ public getAllDimensions(): Environment.SelectedDimensions {
149
+ return this.options.dimensions
132
150
  }
133
151
 
134
- public applySystemMiddleware<
135
- N extends Environment.SystemMiddlewareName,
136
- A extends Parameters<Exclude<Environment.SystemMiddleware[N], undefined>>,
137
- >(name: N, ...args: A): ReturnType<Exclude<Environment.SystemMiddleware[N], undefined>> | A {
138
- const middleware: Environment.SystemMiddleware[N] = this.names[name]
139
- if (typeof middleware === 'function') {
140
- return (middleware as (...args: A) => any)(...args)
152
+ public withDimensions(dimensions: Environment.SelectedDimensions): Environment {
153
+ const newDimensions = {
154
+ ...this.options.dimensions,
155
+ ...dimensions,
141
156
  }
142
- return args
157
+ if (equal(newDimensions, this.options.dimensions)) {
158
+ return this
159
+ }
160
+ return new Environment({ ...this.options, dimensions: newDimensions })
161
+ }
162
+
163
+ public getSchema(): Schema {
164
+ if (!this.options.schema) {
165
+ throw new BindingError('Schema is not set')
166
+ }
167
+ return this.options.schema
168
+ }
169
+
170
+ public withSchema(schema: Schema): Environment {
171
+ return new Environment({ ...this.options, schema })
172
+ }
173
+
174
+ public getParent(): Environment {
175
+ if (!this.options.parent) {
176
+ throw new BindingError('There is no parent environment')
177
+ }
178
+ return this.options.parent
179
+ }
180
+
181
+ public merge(other: Environment): Environment {
182
+ if (other === this) {
183
+ return this
184
+ }
185
+ if (!equal(this.options.node, other.options.node)) {
186
+ throw new BindingError(`Cannot merge two environments with different tree position.`)
187
+ }
188
+ if (this.options.parameters !== other.options.parameters) {
189
+ throw new BindingError(`Cannot merge two environments with different parameters.`)
190
+ }
191
+ if (this.options.dimensions !== other.options.dimensions) {
192
+ throw new BindingError(`Cannot merge two environments with different dimensions.`)
193
+ }
194
+ if (equal(this.options.variables, other.options.variables) && this.options.parent === other.options.parent) {
195
+ return this
196
+ }
197
+ for (const key in other.options.variables) {
198
+ if (key in this.options.variables && !equal(this.options.variables[key], other.options.variables[key])) {
199
+ throw new BindingError(`Cannot merge two environments with different value of variable ${key}:\n`
200
+ + JSON.stringify(this.options.variables[key]) + '\n'
201
+ + JSON.stringify(other.options.variables[key]))
202
+ }
203
+ }
204
+
205
+ return new Environment({
206
+ ...this.options,
207
+ parent: this.options.parent && other.options.parent ? this.options.parent.merge(other.options.parent) : undefined,
208
+ variables: { ...this.options.variables, ...other.options.variables },
209
+ })
143
210
  }
144
211
  }
145
212
 
146
213
  namespace Environment {
147
- export type Name = string | number
214
+ export type Name = string
148
215
 
149
216
  export type Value = ReactNode
150
217
 
151
- export interface SystemVariables {
152
- labelMiddleware?: (label: ReactNode) => ReactNode
153
- rootWhere?: UniqueWhere
154
- rootWhereAsFilter?: Filter
155
- rootShouldExists?: 'no' | 'maybe' | 'yes'
218
+ export type ResolvedValue = Value | Filter
219
+
220
+ export interface Options {
221
+ node?: AnyNode
222
+ schema?: Schema
223
+ dimensions: SelectedDimensions
224
+ parameters: Parameters
225
+ variables: CustomVariables
226
+ parent?: Environment
156
227
  }
157
228
 
158
- export const systemVariableNames: Set<SystemVariableName> = new Set([
159
- 'labelMiddleware',
160
- 'rootWhere',
161
- 'rootWhereAsFilter',
162
- 'rootShouldExists',
163
- ])
229
+ export type SubTreeNode =
230
+ | SubTreeEntityNode
231
+ | SubTreeEntityListNode
164
232
 
165
- export const reservedVariableNames: Set<string> = new Set([
166
- ...systemVariableNames,
167
- 'dimensions',
168
- ])
233
+ export type InnerNode =
234
+ | EntityNode
235
+ | EntityListNode
236
+ | ColumnNode
169
237
 
170
- export type SystemVariableName = keyof SystemVariables
238
+ export type AnyNode =
239
+ | SubTreeNode
240
+ | InnerNode
171
241
 
172
- export interface SelectedDimensions {
173
- [key: string]: string[]
242
+ export interface SubTreeEntityNode {
243
+ type: 'subtree-entity'
244
+ entity: SchemaEntity
245
+ expectedCardinality: 'zero' | 'one' | 'zero-or-one'
246
+ filter: Filter
174
247
  }
175
248
 
176
- export interface NameStore extends SystemVariables {
177
- dimensions: SelectedDimensions
249
+ export interface SubTreeEntityListNode {
250
+ type: 'subtree-entity-list'
251
+ entity: SchemaEntity
252
+ expectedCardinality: 'zero-to-many' | 'zero'
253
+ filter: Filter
254
+ }
255
+
256
+ export interface EntityNode {
257
+ type: 'entity'
258
+ entity: SchemaEntity
259
+ field: SchemaRelation
260
+ }
178
261
 
179
- [name: string]: Value
262
+ export interface EntityListNode {
263
+ type: 'entity-list'
264
+ entity: SchemaEntity
265
+ field: SchemaRelation
180
266
  }
181
267
 
182
- export type DeltaFactory = { [N in string]: ((environment: Environment) => Environment.Value) | Environment.Value } &
183
- { [N in keyof SystemVariables]?: SystemVariables[N] }
268
+ export interface ColumnNode {
269
+ type: 'column'
270
+ entity: SchemaEntity
271
+ field: SchemaColumn
272
+ }
184
273
 
185
- export type SystemMiddleware = {
186
- [N in SystemMiddlewareName]: SystemVariables[N]
274
+ export interface SelectedDimensions {
275
+ [key: string]: string[]
187
276
  }
188
277
 
189
- export type SystemMiddlewareName = 'labelMiddleware'
278
+ export interface Parameters {
279
+ [key: string]: string | undefined
280
+ }
190
281
 
191
- export const defaultSystemVariables: SystemVariables = {
192
- labelMiddleware: label => label,
282
+ export interface CustomVariables {
283
+ [key: string]: Value
193
284
  }
194
285
 
195
- export const defaultNameStore: NameStore = {
196
- ...defaultSystemVariables,
197
- dimensions: {},
286
+ export interface ValuesMapWithFactory {
287
+ [key: string]:
288
+ | ((environment: Environment) => Value)
289
+ | Value
198
290
  }
291
+
292
+ /** @deprecated */
293
+ export type DeltaFactory = ValuesMapWithFactory
199
294
  }
200
295
 
201
296
  export { Environment }
@@ -0,0 +1,228 @@
1
+ import { Environment } from './Environment'
2
+ import {
3
+ HasOneRelation,
4
+ SugaredQualifiedEntityList,
5
+ SugaredQualifiedSingleEntity,
6
+ SugaredRelativeEntityList,
7
+ SugaredRelativeSingleEntity,
8
+ SugaredRelativeSingleField,
9
+ SugaredUnconstrainedQualifiedEntityList,
10
+ SugaredUnconstrainedQualifiedSingleEntity,
11
+ } from '../treeParameters'
12
+ import { QueryLanguage } from '../queryLanguage'
13
+ import { BindingError } from '../BindingError'
14
+ import { NIL_UUID } from '../bindingTypes'
15
+ import { whereToFilter } from '@contember/client'
16
+ import { BaseRelation, Schema, SchemaColumn, SchemaEntity, SchemaField, SchemaRelation } from '../core/schema'
17
+ import levenshtein from 'js-levenshtein'
18
+
19
+ export class TreeNodeEnvironmentFactory {
20
+
21
+ public static createEnvironmentForEntityListSubtree(
22
+ environment: Environment,
23
+ sugaredEntityList: SugaredQualifiedEntityList | SugaredUnconstrainedQualifiedEntityList,
24
+ ): Environment {
25
+ let entityList
26
+ let rootWhere
27
+ let expectedCardinality: Environment.SubTreeNode['expectedCardinality']
28
+
29
+ if (sugaredEntityList.isCreating) {
30
+ entityList = QueryLanguage.desugarUnconstrainedQualifiedEntityList(sugaredEntityList, environment)
31
+ rootWhere = { id: { eq: NIL_UUID } } as const
32
+ expectedCardinality = 'zero'
33
+
34
+ } else {
35
+ entityList = QueryLanguage.desugarQualifiedEntityList(sugaredEntityList, environment)
36
+ rootWhere = entityList.filter ?? {}
37
+ expectedCardinality = 'zero-to-many'
38
+ }
39
+
40
+ const entitySchema = this.resolveEntity(environment.getSchema(), entityList.entityName, 'entity list')
41
+
42
+ return environment.withSubTree({
43
+ type: 'subtree-entity-list',
44
+ entity: entitySchema,
45
+ expectedCardinality,
46
+ filter: rootWhere,
47
+ })
48
+ }
49
+
50
+ public static createEnvironmentForEntitySubtree(
51
+ environment: Environment,
52
+ sugaredEntityList: SugaredQualifiedSingleEntity | SugaredUnconstrainedQualifiedSingleEntity,
53
+ ): Environment {
54
+ let entity
55
+ let rootWhere
56
+ let expectedCardinality: Environment.SubTreeNode['expectedCardinality']
57
+
58
+ if (sugaredEntityList.isCreating) {
59
+ rootWhere = { id: { eq: NIL_UUID } } as const
60
+ expectedCardinality = 'zero'
61
+ entity = QueryLanguage.desugarUnconstrainedQualifiedSingleEntity(sugaredEntityList, environment)
62
+
63
+ } else {
64
+ entity = QueryLanguage.desugarQualifiedSingleEntity(sugaredEntityList, environment, { missingSetOnCreate: 'fill' })
65
+ rootWhere = whereToFilter(entity.where)
66
+ expectedCardinality = entity.setOnCreate ? 'zero-or-one' : 'one'
67
+ }
68
+
69
+ const entitySchema = this.resolveEntity(environment.getSchema(), entity.entityName, 'entity')
70
+
71
+ return environment.withSubTree({
72
+ type: 'subtree-entity',
73
+ entity: entitySchema,
74
+ expectedCardinality: expectedCardinality,
75
+ filter: rootWhere,
76
+ })
77
+ }
78
+
79
+ public static createEnvironmentForEntityList(
80
+ environment: Environment,
81
+ sugaredRelativeEntityList: SugaredRelativeEntityList,
82
+ ): Environment {
83
+ const relativeEntityList = QueryLanguage.desugarRelativeEntityList(sugaredRelativeEntityList, environment)
84
+ const hasOneEnvironment = this.traverseHasOnePath(environment, relativeEntityList.hasOneRelationPath)
85
+ const hasManyField = relativeEntityList.hasManyRelation.field
86
+
87
+ const field = this.assertHasManyRelation(hasOneEnvironment, hasManyField)
88
+
89
+ const targetEntity = environment.getSchema().getEntity(field.targetEntity)
90
+ if (!targetEntity) {
91
+ throw new BindingError('should not happen')
92
+ }
93
+ return hasOneEnvironment.withSubTreeChild({
94
+ type: 'entity-list',
95
+ field,
96
+ entity: targetEntity,
97
+ })
98
+ }
99
+
100
+ public static createEnvironmentForEntity(
101
+ environment: Environment,
102
+ sugaredRelativeSingleEntity: SugaredRelativeSingleEntity,
103
+ ) {
104
+ const relativeSingleEntity = QueryLanguage.desugarRelativeSingleEntity(sugaredRelativeSingleEntity, environment)
105
+
106
+ return this.traverseHasOnePath(environment, relativeSingleEntity.hasOneRelationPath)
107
+ }
108
+
109
+ public static createEnvironmentForField(
110
+ environment: Environment,
111
+ sugaredRelativeSingleField: SugaredRelativeSingleField,
112
+ ) {
113
+ const relativeSingleField = QueryLanguage.desugarRelativeSingleField(sugaredRelativeSingleField, environment)
114
+ const hasOneEnvironment = this.traverseHasOnePath(environment, relativeSingleField.hasOneRelationPath)
115
+
116
+ const field = this.resolveColumn(hasOneEnvironment, relativeSingleField.field)
117
+
118
+ return hasOneEnvironment.withSubTreeChild({
119
+ type: 'column',
120
+ entity: environment.getSubTreeNode().entity,
121
+ field,
122
+ })
123
+ }
124
+
125
+ private static traverseHasOnePath(
126
+ environment: Environment,
127
+ hasOneRelationPath: HasOneRelation[],
128
+ ): Environment {
129
+ for (const pathItem of hasOneRelationPath) {
130
+ const field = this.resolveHasOneRelation(environment, pathItem.field, !!pathItem.reducedBy)
131
+ const targetEntity = environment.getSchema().getEntity(field.targetEntity)
132
+ if (!targetEntity) {
133
+ throw new BindingError('should not happen')
134
+ }
135
+ environment = environment.withSubTreeChild({
136
+ type: 'entity',
137
+ field,
138
+ entity: targetEntity,
139
+ })
140
+ }
141
+ return environment
142
+ }
143
+
144
+ private static resolveHasOneRelation(environment: Environment, field: string, isReduced: boolean): SchemaRelation {
145
+ if (isReduced) {
146
+ return this.resolveRelation(environment, field, 'reduced has-one relation', ['ManyHasMany', 'OneHasMany'])
147
+ }
148
+ return this.resolveRelation(environment, field, 'a has-one relation', ['ManyHasOne', 'OneHasOne'])
149
+ }
150
+
151
+ private static assertHasManyRelation(environment: Environment, field: string): SchemaRelation {
152
+ return this.resolveRelation(environment, field, 'a has-many relation', ['ManyHasMany', 'OneHasMany'])
153
+ }
154
+
155
+
156
+ private static resolveRelation(environment: Environment, field: string, relationDescription: string, expectedRelationType: BaseRelation['type'][]): SchemaRelation {
157
+ return this.resolveField(environment, field, (field): field is SchemaRelation => {
158
+ return field.__typename === '_Relation' && expectedRelationType.includes(field.type)
159
+ }, relationDescription)
160
+ }
161
+
162
+ private static resolveEntity(schema: Schema, entityName: string, type: 'entity' | 'entity list'): SchemaEntity {
163
+ const entity = schema.getEntity(entityName)
164
+ if (!entity) {
165
+ const alternative = this.recommendAlternative(entityName, schema.store.entities.keys())
166
+ const didYouMean = alternative ? `Did you mean '${alternative}'?` : ''
167
+ throw new BindingError(`Invalid ${type} sub tree: Entity '${entityName}' doesn't exist. ${didYouMean}`)
168
+ }
169
+ return entity
170
+ }
171
+
172
+ private static resolveColumn(environment: Environment, fieldName: string): SchemaColumn {
173
+ return this.resolveField(environment, fieldName, (field): field is SchemaColumn => field.__typename === '_Column', 'an ordinary field')
174
+ // TODO check that defaultValue matches the type
175
+ // TODO run custom validators
176
+ }
177
+
178
+ private static resolveField<T extends SchemaField>(environment: Environment, fieldName: string, matcher: (field: SchemaField) => field is T, expectedDescription: string): T {
179
+ const treeLocation = environment.getSubTreeNode()
180
+ const entity = treeLocation.entity
181
+ const field = entity.fields.get(fieldName)
182
+ if (!field) {
183
+ const alternative = this.recommendAlternative(
184
+ fieldName,
185
+ Array.from(entity.fields)
186
+ .filter(([, field]) => matcher(field))
187
+ .map(([fieldName]) => fieldName),
188
+ )
189
+ const didYouMean = alternative ? `Did you mean '${alternative}'?` : ''
190
+ throw new BindingError(`Field '${fieldName}' doesn't exist on ${this.describeLocation(environment)}. ${didYouMean}`)
191
+ }
192
+ if (!matcher(field)) {
193
+ const actual = field.__typename === '_Column' ? 'an ordinary field' : `a ${field.type} relation`
194
+ throw new BindingError(
195
+ `Invalid field: the name '${field.name}' on ${this.describeLocation(environment)} ` +
196
+ `refers to ${actual} but is being used as a ${expectedDescription}.`,
197
+ )
198
+ }
199
+ return field
200
+ }
201
+
202
+ private static describeLocation(environment: Environment): string {
203
+ const path = []
204
+ for (let env = environment;; env = env.getParent()) {
205
+ const node = env.getSubTreeNode()
206
+ if (node.type === 'subtree-entity' || node.type === 'subtree-entity-list') {
207
+ const pathText = path.length ? ` in path ${path.join('.')}` : ''
208
+ return `entity '${node.entity.name}'${pathText}`
209
+ }
210
+ path.push(node.field.name)
211
+ }
212
+ }
213
+
214
+ public static recommendAlternative(original: string, possibleAlternatives: Iterable<string>): string | undefined {
215
+ let bestAlternative: string | undefined = undefined
216
+ let bestAlternativeDistance = Number.MAX_SAFE_INTEGER
217
+
218
+ for (const alternative of possibleAlternatives) {
219
+ const distance = levenshtein(original, alternative)
220
+
221
+ if (distance < bestAlternativeDistance) {
222
+ bestAlternative = alternative
223
+ bestAlternativeDistance = distance
224
+ }
225
+ }
226
+ return bestAlternative
227
+ }
228
+ }