@workbasehq/core 0.0.0 → 0.1.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.
- package/LICENSE +202 -0
- package/NOTICE +4 -0
- package/package.json +62 -1
- package/src/account-provisioning.ts +24 -0
- package/src/admin-forms.tsx +70 -0
- package/src/admin-security.ts +63 -0
- package/src/admin-ui.tsx +438 -0
- package/src/app.ts +115 -0
- package/src/audit-event.ts +23 -0
- package/src/audit.ts +35 -0
- package/src/authorization-api.ts +3 -0
- package/src/authorization.ts +135 -0
- package/src/authorized-execution.ts +15 -0
- package/src/bootstrap.ts +23 -0
- package/src/browser-dispatch.ts +19 -0
- package/src/calendar-display.ts +26 -0
- package/src/capabilities.ts +41 -0
- package/src/commands.ts +46 -0
- package/src/config-proposal-contract.ts +16 -0
- package/src/config-proposals.ts +95 -0
- package/src/config-shorthand.ts +200 -0
- package/src/config.ts +286 -0
- package/src/console-contract.ts +105 -0
- package/src/console-contribution.ts +7 -0
- package/src/console.ts +84 -0
- package/src/crud.ts +146 -0
- package/src/crypto.ts +33 -0
- package/src/detail-display.ts +59 -0
- package/src/detail-layout.ts +17 -0
- package/src/errors.ts +3 -0
- package/src/event-delivery.ts +76 -0
- package/src/events.ts +11 -0
- package/src/execution/atomic.ts +70 -0
- package/src/execution/compiler.ts +55 -0
- package/src/execution/context.ts +100 -0
- package/src/execution/d1.ts +46 -0
- package/src/execution/errors.ts +21 -0
- package/src/execution/index.ts +6 -0
- package/src/execution/outbox.ts +8 -0
- package/src/execution/permissions.ts +9 -0
- package/src/execution/policies.ts +156 -0
- package/src/execution/policy-receipts.ts +51 -0
- package/src/execution/types.ts +74 -0
- package/src/execution/workflow.ts +35 -0
- package/src/form-display.ts +36 -0
- package/src/idempotency.ts +10 -0
- package/src/identity-providers.ts +2 -0
- package/src/identity-settings.ts +42 -0
- package/src/identity-writes.ts +14 -0
- package/src/identity.ts +2 -0
- package/src/index.ts +32 -0
- package/src/json-csrf.ts +22 -0
- package/src/kernel/adapters/tenancy.ts +8 -0
- package/src/kernel/audit-port.ts +12 -0
- package/src/kernel/builtin-source.ts +34 -0
- package/src/kernel/composition.ts +77 -0
- package/src/kernel/identity-port.ts +36 -0
- package/src/kernel/mail-outbox-port.ts +23 -0
- package/src/kernel/migrations.ts +76 -0
- package/src/kernel/operation-name.ts +8 -0
- package/src/kernel/plugin.ts +92 -0
- package/src/kernel/predicate.ts +69 -0
- package/src/kernel/registry.ts +198 -0
- package/src/kernel/schema-check.ts +13 -0
- package/src/logging.ts +21 -0
- package/src/migrations/better-auth-schema.ts +2 -0
- package/src/migrations/email-delivery-schema.ts +6 -0
- package/src/migrations/planner.ts +77 -0
- package/src/migrations/schema.ts +85 -0
- package/src/migrations/version-contract.ts +28 -0
- package/src/migrations/versions.ts +90 -0
- package/src/ops-schema.ts +13 -0
- package/src/ops.ts +34 -0
- package/src/organization-permissions.ts +13 -0
- package/src/organization-rules.ts +25 -0
- package/src/organizations.ts +43 -0
- package/src/plugins.ts +3 -0
- package/src/policies.ts +186 -0
- package/src/public-schema.ts +65 -0
- package/src/query/compiler.ts +395 -0
- package/src/query/cursor.ts +43 -0
- package/src/query/enum-labels.json +16 -0
- package/src/query/enum-values.ts +7 -0
- package/src/query/errors.ts +10 -0
- package/src/query/executor.ts +118 -0
- package/src/query/facade.ts +34 -0
- package/src/query/labels.ts +105 -0
- package/src/query/limits.ts +8 -0
- package/src/query/observability.ts +49 -0
- package/src/query/routes.ts +60 -0
- package/src/query/schema.ts +216 -0
- package/src/query/search.ts +15 -0
- package/src/relay.ts +65 -0
- package/src/request-timing.ts +71 -0
- package/src/schema-compatibility.ts +43 -0
- package/src/scope-operations.ts +3 -0
- package/src/session-contract.ts +1 -0
- package/src/types.ts +30 -0
- package/src/worker-fetch.ts +14 -0
- package/src/workflow-routes.ts +156 -0
- package/src/workflow-runtime.ts +327 -0
- package/src/workflow-schema.ts +29 -0
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
/** Pure authoring layer. All imports are erased; the kernel validates the expanded input. */
|
|
2
|
+
import type { InstanceInput, Operation } from './config'
|
|
3
|
+
|
|
4
|
+
type EntityInput = InstanceInput['entities'][string]
|
|
5
|
+
type FieldInput = EntityInput['fields'][string]
|
|
6
|
+
type RelationInput = NonNullable<EntityInput['relations']>[string]
|
|
7
|
+
type CanonicalPolicy = NonNullable<InstanceInput['policies']>[string][string]
|
|
8
|
+
type ScalarToken = 'string' | 'text' | 'int' | 'float' | 'bool' | 'datetime'
|
|
9
|
+
export type FieldShorthand = ScalarToken | `${ScalarToken}!` | `ref:${string}` | `enum:${string}`
|
|
10
|
+
export type RelationShorthand = `${string}@${string}`
|
|
11
|
+
export type ShorthandEntity = Omit<EntityInput, 'fields' | 'relations' | 'displayField'> & {
|
|
12
|
+
displayField?: string | false
|
|
13
|
+
fields: Record<string, FieldInput | FieldShorthand>
|
|
14
|
+
relations?: Record<string, RelationInput | RelationShorthand>
|
|
15
|
+
}
|
|
16
|
+
export type OperationShorthand = Operation[] | 'all' | 'read' | '*'
|
|
17
|
+
export interface PermissionDeclaration { role: string; entity: string; operations: OperationShorthand }
|
|
18
|
+
export type PermissionShorthand = Record<string, Record<string, OperationShorthand>> | PermissionDeclaration[]
|
|
19
|
+
export interface PolicyScope { name: string; where: Record<string, unknown> }
|
|
20
|
+
export type PolicyShorthand = CanonicalPolicy | `scope:${string}` | { scope: string; deny?: 'empty' | 'forbidden'; fields?: string[] }
|
|
21
|
+
export type ShorthandInput = Omit<InstanceInput, 'entities' | 'permissions' | 'policies'> & {
|
|
22
|
+
entities: Record<string, ShorthandEntity>
|
|
23
|
+
permissions: PermissionShorthand
|
|
24
|
+
policies?: Record<string, Record<string, PolicyShorthand>>
|
|
25
|
+
enums?: Record<string, readonly string[]>
|
|
26
|
+
policyScopes?: PolicyScope[]
|
|
27
|
+
}
|
|
28
|
+
const all: Operation[] = ['read', 'create', 'update', 'delete']
|
|
29
|
+
const identifier = /^[a-z][a-z0-9_]*$/
|
|
30
|
+
const own = (object: object, key: string) => Object.hasOwn(object, key)
|
|
31
|
+
|
|
32
|
+
/** Same Boolean constant rules as policies.constantPredicate, on the filter grammar.
|
|
33
|
+
* Relation existence is never inferred from database state. Canonical schema validation
|
|
34
|
+
* still validates the complete filter after expansion; this only rejects certain truths.
|
|
35
|
+
* Entity context follows nested relation targets; declarations without it stay conservative.
|
|
36
|
+
*/
|
|
37
|
+
export function constantFilter(filter: Record<string, unknown>, relations: Record<string, unknown>, entities: Record<string, { relations?: Record<string, unknown> }> = {}): boolean | undefined {
|
|
38
|
+
const values = Object.entries(filter).map(([key, value]): boolean | undefined => {
|
|
39
|
+
if (key === 'and' || key === 'or') {
|
|
40
|
+
if (!Array.isArray(value)) return undefined
|
|
41
|
+
const children = value.map(child => child && typeof child === 'object' && !Array.isArray(child) ? constantFilter(child, relations, entities) : undefined)
|
|
42
|
+
return key === 'and'
|
|
43
|
+
? children.includes(false) ? false : children.every(child => child === true) ? true : undefined
|
|
44
|
+
: children.includes(true) ? true : children.every(child => child === false) ? false : undefined
|
|
45
|
+
}
|
|
46
|
+
if (key === 'not' && value && typeof value === 'object' && !Array.isArray(value)) {
|
|
47
|
+
const child = constantFilter(value as Record<string, unknown>, relations, entities)
|
|
48
|
+
return child === undefined ? undefined : !child
|
|
49
|
+
}
|
|
50
|
+
if (own(relations, key) && value && typeof value === 'object' && !Array.isArray(value)) {
|
|
51
|
+
const relation = relations[key] as RelationInput
|
|
52
|
+
const childRelations = entities[relation.entity]?.relations ?? {}
|
|
53
|
+
const none = !!relation.many && own(value, 'none')
|
|
54
|
+
const child = relation.many ? (value as Record<string, unknown>)[none ? 'none' : 'some'] : value
|
|
55
|
+
if (!child || typeof child !== 'object' || Array.isArray(child)) return undefined
|
|
56
|
+
// To-one also renders as EXISTS: missing parents make it false, even for a true child.
|
|
57
|
+
return constantQuantifier(none, constantFilter(child as Record<string, unknown>, childRelations, entities))
|
|
58
|
+
}
|
|
59
|
+
if (!own(relations, key) && value && typeof value === 'object' && 'in' in value && Array.isArray(value.in) && !value.in.length) return false
|
|
60
|
+
return undefined
|
|
61
|
+
})
|
|
62
|
+
return values.includes(false) ? false : values.every(value => value === true) ? true : undefined
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Canonical input is an identity transform. Sugar is removed before schema validation. */
|
|
66
|
+
export function expand(input: ShorthandInput): InstanceInput {
|
|
67
|
+
let sugar = input.enums !== undefined || input.policyScopes !== undefined || Array.isArray(input.permissions)
|
|
68
|
+
sugar ||= Object.values(input.entities ?? {}).some(entity => entity.displayField === false || Object.values(entity.fields ?? {}).some(field => typeof field === 'string') || Object.values(entity.relations ?? {}).some(relation => typeof relation === 'string'))
|
|
69
|
+
sugar ||= Object.entries(input.permissions ?? {}).some(([role, grants]) => role === '*' || Object.entries(grants).some(([entity, operations]) => entity === '*' || typeof operations === 'string'))
|
|
70
|
+
sugar ||= Object.entries(input.policies ?? {}).some(([entity, roles]) => entity === '*' || Object.entries(roles).some(([role, policy]) => role === '*' || typeof policy === 'string' && policy.startsWith('scope:') || typeof policy === 'object' && policy !== null && 'scope' in policy))
|
|
71
|
+
if (!sugar) return input as InstanceInput
|
|
72
|
+
for (const [name, values] of Object.entries(input.enums ?? {})) {
|
|
73
|
+
if (!Array.isArray(values)) throw new Error(`Invalid enum ${name}: not an array`)
|
|
74
|
+
if (!values.length) throw new Error(`Invalid enum ${name}: empty`)
|
|
75
|
+
if (values.some(value => typeof value !== 'string')) throw new Error(`Invalid enum ${name}: non-string value`)
|
|
76
|
+
if (values.some(value => !value.trim())) throw new Error(`Invalid enum ${name}: empty value`)
|
|
77
|
+
if (new Set(values).size !== values.length) throw new Error(`Invalid enum ${name}: duplicate value`)
|
|
78
|
+
}
|
|
79
|
+
const entities: InstanceInput['entities'] = Object.fromEntries(Object.entries(input.entities).map(([name, entity]) => {
|
|
80
|
+
let entitySugar = false
|
|
81
|
+
const fields: EntityInput['fields'] = Object.fromEntries(Object.entries(entity.fields).map(([key, field]) => {
|
|
82
|
+
if (typeof field !== 'string') return [key, field]
|
|
83
|
+
sugar = entitySugar = true
|
|
84
|
+
const match = /^(string|text|int|float|bool|datetime|ref:[a-z][a-z0-9_]*|enum:[a-z][a-z0-9_]*)(!)?$/.exec(field)
|
|
85
|
+
if (!match) throw new Error(`Unknown field shorthand: ${name}.${key}: ${field}`)
|
|
86
|
+
const token = match[1]; const required = match[2] ? { required: true } : {}
|
|
87
|
+
if (token.startsWith('ref:')) {
|
|
88
|
+
const target = token.slice(4)
|
|
89
|
+
if (!own(input.entities, target)) throw new Error(`Unknown reference: ${name}.${key} -> ${target}`)
|
|
90
|
+
return [key, { type: 'ref', entity: target, ...required }]
|
|
91
|
+
}
|
|
92
|
+
if (token.startsWith('enum:')) {
|
|
93
|
+
const enumName = token.slice(5)
|
|
94
|
+
if (!input.enums || !own(input.enums, enumName)) throw new Error(`Unknown enum: ${name}.${key} -> ${enumName}`)
|
|
95
|
+
return [key, { type: 'enum', values: [...input.enums[enumName]], ...required }]
|
|
96
|
+
}
|
|
97
|
+
return [key, { type: token as ScalarToken, ...required }]
|
|
98
|
+
}))
|
|
99
|
+
const relations: NonNullable<EntityInput['relations']> = Object.fromEntries(Object.entries(entity.relations ?? {}).map(([key, relation]) => {
|
|
100
|
+
if (typeof relation !== 'string') return [key, relation]
|
|
101
|
+
sugar = entitySugar = true
|
|
102
|
+
const match = /^([a-z][a-z0-9_]*)@([a-z][a-z0-9_]*)(\[\])?$/.exec(relation)
|
|
103
|
+
if (!match) throw new Error(`Invalid relation shorthand: ${name}.${key}: ${relation}`)
|
|
104
|
+
const [, target, field, many] = match
|
|
105
|
+
return [key, { entity: target, field, ...(many ? { many: true } : {}) }]
|
|
106
|
+
}))
|
|
107
|
+
const displayField = entity.displayField ?? (entitySugar ? ['name', 'title'].find(key => own(fields, key)) : undefined)
|
|
108
|
+
const { fields: _fields, relations: _relations, displayField: _display, ...options } = entity
|
|
109
|
+
return [name, { ...options, fields, ...(entity.relations ? { relations } : {}), ...(displayField ? { displayField } : {}) }]
|
|
110
|
+
}))
|
|
111
|
+
// Validate sugar references after all field tokens have expanded (including reverse FKs).
|
|
112
|
+
for (const [name, entity] of Object.entries(input.entities)) for (const [key, relation] of Object.entries(entity.relations ?? {})) {
|
|
113
|
+
if (typeof relation !== 'string') continue
|
|
114
|
+
const expanded = entities[name].relations![key]
|
|
115
|
+
const field = expanded.many ? entities[expanded.entity]?.fields[expanded.field] : entities[name].fields[expanded.field]
|
|
116
|
+
if (!field || field.type !== 'ref' || field.entity !== (expanded.many ? name : expanded.entity) || !own(entities, expanded.entity)) throw new Error(`Invalid relation reference: ${name}.${key} (${expanded.entity}.${expanded.field})`)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const declarations = Array.isArray(input.permissions) ? input.permissions : Object.entries(input.permissions).flatMap(([role, grants]) => Object.entries(grants).map(([entity, operations]) => ({ role, entity, operations })))
|
|
120
|
+
const explicit = new Map<string, Operation[]>()
|
|
121
|
+
const wildcard = new Map<string, Operation[]>()
|
|
122
|
+
const permissions: InstanceInput['permissions'] = {}
|
|
123
|
+
for (const declaration of declarations) {
|
|
124
|
+
if (!declaration || typeof declaration !== 'object' || Object.keys(declaration).some(key => !['role', 'entity', 'operations'].includes(key)) || typeof declaration.role !== 'string' || typeof declaration.entity !== 'string') throw new Error('Invalid permission declaration: expected role, entity and operations')
|
|
125
|
+
const { role, entity, operations } = declaration
|
|
126
|
+
const isWildcard = role === '*' || entity === '*'
|
|
127
|
+
if (isWildcard || typeof operations === 'string') sugar = true
|
|
128
|
+
if (role !== '*' && !input.roles.includes(role)) throw new Error(`Unknown permission role: ${role} (${entity})`)
|
|
129
|
+
if (entity !== '*' && !own(entities, entity)) throw new Error(`Unknown permission entity: ${role}.${entity}`)
|
|
130
|
+
const ops = operations === 'all' || operations === '*' ? [...all] : operations === 'read' ? ['read'] as Operation[] : operations
|
|
131
|
+
if (!Array.isArray(ops) || ops.some(operation => !all.includes(operation))) throw new Error(`Unknown permission operation: ${role}.${entity}`)
|
|
132
|
+
for (const r of role === '*' ? input.roles : [role]) for (const e of entity === '*' ? Object.keys(entities) : [entity]) {
|
|
133
|
+
const key = `${r}.${e}`; const target = isWildcard ? wildcard : explicit
|
|
134
|
+
if (target.has(key)) throw new Error(`Duplicate permission declaration: ${r}.${e}`)
|
|
135
|
+
target.set(key, [...ops])
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
for (const role of input.roles) {
|
|
139
|
+
const grants: Record<string, Operation[]> = {}
|
|
140
|
+
for (const entity of Object.keys(entities)) {
|
|
141
|
+
const key = `${role}.${entity}`; const ops = explicit.get(key) ?? wildcard.get(key)
|
|
142
|
+
if (ops) grants[entity] = ops
|
|
143
|
+
}
|
|
144
|
+
if (Object.keys(grants).length || !Array.isArray(input.permissions) && own(input.permissions, role)) permissions[role] = grants
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const scopes = new Map<string, Record<string, unknown>>()
|
|
148
|
+
for (const scope of input.policyScopes ?? []) {
|
|
149
|
+
if (!scope || typeof scope !== 'object') throw new Error('Invalid policy scope declaration')
|
|
150
|
+
for (const key of Object.keys(scope)) if (!['name', 'where'].includes(key)) throw new Error(`Invalid policy scope ${scope.name}: unknown option ${key}`)
|
|
151
|
+
if (typeof scope.name !== 'string' || !identifier.test(scope.name)) throw new Error(`Invalid policy scope name: ${scope.name}`)
|
|
152
|
+
if (scopes.has(scope.name)) throw new Error(`Duplicate policy scope: ${scope.name}`)
|
|
153
|
+
if (!scope.where || !Object.keys(scope.where).length) throw new Error(`Empty policy scope: ${scope.name}`)
|
|
154
|
+
if (constantFilter(scope.where, {}) === true) throw new Error(`Empty policy scope (always true): ${scope.name}`)
|
|
155
|
+
scopes.set(scope.name, scope.where)
|
|
156
|
+
}
|
|
157
|
+
const usedScopes = new Set<string>()
|
|
158
|
+
const policies: NonNullable<InstanceInput['policies']> = {}
|
|
159
|
+
for (const [entity, roles] of Object.entries(input.policies ?? {})) {
|
|
160
|
+
if (entity !== '*' && !own(entities, entity)) throw new Error(`Unknown policy entity: ${entity}`)
|
|
161
|
+
for (const [role, policy] of Object.entries(roles)) {
|
|
162
|
+
if (role !== '*' && !input.roles.includes(role)) throw new Error(`Unknown policy role: ${entity}.${role}`)
|
|
163
|
+
if (entity === '*' || role === '*') {
|
|
164
|
+
sugar = true
|
|
165
|
+
if (policy !== 'none') throw new Error(`Policy wildcard must be none: ${entity}.${role}`)
|
|
166
|
+
continue // Totalization below fills every otherwise missing pair with none.
|
|
167
|
+
}
|
|
168
|
+
let value: CanonicalPolicy
|
|
169
|
+
if (typeof policy === 'string' && policy.startsWith('scope:') || typeof policy === 'object' && policy !== null && 'scope' in policy) {
|
|
170
|
+
sugar = true
|
|
171
|
+
if (typeof policy === 'object') for (const key of Object.keys(policy)) if (!['scope', 'deny', 'fields'].includes(key)) throw new Error(`Unknown policy scope option: ${entity}.${role}.${key}`)
|
|
172
|
+
if (typeof policy === 'object') {
|
|
173
|
+
if (typeof policy.scope !== 'string' || !identifier.test(policy.scope)) throw new Error(`Invalid policy ${entity}.${role}: scope must be an identifier`)
|
|
174
|
+
if (own(policy, 'deny') && !['empty', 'forbidden'].includes(policy.deny!)) throw new Error(`Invalid policy ${entity}.${role}: deny must be empty or forbidden`)
|
|
175
|
+
if (own(policy, 'fields') && (!Array.isArray(policy.fields) || policy.fields.some(field => typeof field !== 'string' || !['id', 'organization_id', 'created_at', 'updated_at', 'version'].includes(field) && !own(entities[entity].fields, field)))) throw new Error(`Invalid policy ${entity}.${role}: fields must be an array of known field names`)
|
|
176
|
+
}
|
|
177
|
+
const name = typeof policy === 'string' ? policy.slice(6) : policy.scope
|
|
178
|
+
if (!identifier.test(name)) throw new Error(`Invalid policy ${entity}.${role}: scope must be an identifier`)
|
|
179
|
+
const where = scopes.get(name)
|
|
180
|
+
if (!where) throw new Error(`Unknown policy scope: ${entity}.${role} -> ${name}`)
|
|
181
|
+
if (constantFilter(where, entities[entity].relations ?? {}, entities) === true) throw new Error(`Empty policy scope (always true): ${name}`)
|
|
182
|
+
usedScopes.add(name)
|
|
183
|
+
value = typeof policy === 'string' ? { where } : { where, ...(policy.deny ? { deny: policy.deny } : {}), ...(policy.fields ? { fields: [...policy.fields] } : {}) }
|
|
184
|
+
} else value = policy as CanonicalPolicy
|
|
185
|
+
if (!own(policies, entity)) policies[entity] = {}
|
|
186
|
+
policies[entity][role] = value
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
for (const name of scopes.keys()) if (!usedScopes.has(name)) throw new Error(`Unused policy scope: ${name}`)
|
|
190
|
+
if (!sugar) return input as InstanceInput
|
|
191
|
+
const { enums: _enums, policyScopes: _scopes, ...canonical } = input
|
|
192
|
+
return { ...canonical, entities, permissions, policies: Object.fromEntries(Object.keys(entities).map(entity => [entity, Object.fromEntries(input.roles.map(role => [role, policies[entity]?.[role] ?? 'none']))])) }
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** EXISTS/NOT EXISTS over false is constant; over true still depends on related rows.
|
|
196
|
+
* Shared with the compiled predicate fold; no database state is assumed.
|
|
197
|
+
*/
|
|
198
|
+
export function constantQuantifier(negated: boolean, child: boolean | undefined): boolean | undefined {
|
|
199
|
+
return child === false ? negated : undefined
|
|
200
|
+
}
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
import { coreEnums, type CoreRole } from './query/enum-values'
|
|
2
|
+
import { z } from 'zod'
|
|
3
|
+
import { calendarViewsSchema, validateCalendarViews } from './calendar-display'
|
|
4
|
+
import { Q, Fn, Cond, type ISequelizable, type ISerializable } from '@jakub.knejzlik/ts-query'
|
|
5
|
+
import { validateLabelExpressions } from './query/labels'
|
|
6
|
+
import type { WorkbasePlugin } from './kernel/plugin'
|
|
7
|
+
import { resolvePlugins } from './kernel/composition'
|
|
8
|
+
import { expand, type ShorthandInput } from './config-shorthand'
|
|
9
|
+
import { validatePolicies } from './policies'
|
|
10
|
+
import { filterSchema } from './query/schema'
|
|
11
|
+
import { formDisplaySchema, formSectionsSchema, validateFormDisplay } from './form-display'
|
|
12
|
+
import { detailDisplaySchema, validateDetailDisplay } from './detail-display'
|
|
13
|
+
|
|
14
|
+
export { Q, Fn, Cond }
|
|
15
|
+
|
|
16
|
+
export const CORE_VERSION = '0.1.0'
|
|
17
|
+
const navigationIconSchema = z.enum(['LayoutDashboard', 'Users', 'MapPin', 'Coins', 'Wallet', 'ArrowLeftRight', 'Settings', 'Building2', 'Activity', 'Workflow', 'Database', 'Folder'])
|
|
18
|
+
const identifier = z.string().regex(/^[a-z][a-z0-9_]*$/)
|
|
19
|
+
export const fieldSchema = z.object({
|
|
20
|
+
type: z.enum(['string', 'text', 'int', 'float', 'bool', 'datetime', 'enum', 'ref']),
|
|
21
|
+
required: z.boolean().default(false), values: z.array(z.string()).optional(), entity: identifier.optional(),
|
|
22
|
+
default: z.union([z.string(), z.number(), z.boolean(), z.null()]).optional(),
|
|
23
|
+
min: z.number().optional(), readOnly: z.boolean().optional(), sensitive: z.boolean().optional(),
|
|
24
|
+
ui: z.strictObject({
|
|
25
|
+
hidden: z.boolean().optional(),
|
|
26
|
+
format: z.enum(['identifier']).optional(),
|
|
27
|
+
kind: z.enum(['input', 'textarea', 'select', 'boolean', 'number', 'date', 'datetime', 'time', 'colour']).optional(),
|
|
28
|
+
span: z.enum(['half', 'full']).optional(), section: z.string().min(1).optional(),
|
|
29
|
+
signedBy: z.strictObject({ field: identifier, negativeValue: z.string() }).optional(),
|
|
30
|
+
}).optional(),
|
|
31
|
+
renameFrom: identifier.optional(),
|
|
32
|
+
backfillFrom: z.object({ refField: identifier, valueField: identifier }).optional(),
|
|
33
|
+
}).superRefine((f, ctx) => {
|
|
34
|
+
if (f.type === 'enum' && !f.values?.length) ctx.addIssue({ code: 'custom', message: 'enum requires values' })
|
|
35
|
+
if (f.type === 'ref' && !f.entity) ctx.addIssue({ code: 'custom', message: 'ref requires entity' })
|
|
36
|
+
})
|
|
37
|
+
const operations = z.array(z.enum(['read', 'create', 'update', 'delete']))
|
|
38
|
+
export const organizationActions = ['organizations.update', 'members.read', 'members.update', 'members.remove', 'invitations.create', 'invitations.read', 'invitations.revoke', 'tokens.create', 'tokens.read', 'tokens.revoke'] as const
|
|
39
|
+
export type OrganizationAction = typeof organizationActions[number]
|
|
40
|
+
// Every built-in role must make an explicit runtime grant decision. Undefined
|
|
41
|
+
// preserves the absence of a default entry for instance-configured roles.
|
|
42
|
+
const coreOrganizationPermissions: Record<CoreRole, OrganizationAction[] | undefined> = {
|
|
43
|
+
owner: [...organizationActions],
|
|
44
|
+
dispatcher: ['invitations.create', 'invitations.read', 'invitations.revoke'],
|
|
45
|
+
viewer: [],
|
|
46
|
+
administrator: undefined,
|
|
47
|
+
unknown: undefined,
|
|
48
|
+
}
|
|
49
|
+
export const defaultOrganizationPermissions: Record<string, OrganizationAction[]> = Object.fromEntries(
|
|
50
|
+
coreEnums.role.flatMap(role => {
|
|
51
|
+
const grants = coreOrganizationPermissions[role]
|
|
52
|
+
return grants === undefined ? [] : [[role, grants]]
|
|
53
|
+
}),
|
|
54
|
+
)
|
|
55
|
+
const filterKind = z.enum(['text', 'enum', 'relation', 'number', 'date', 'boolean'])
|
|
56
|
+
const listHints = z.strictObject({
|
|
57
|
+
columns: z.array(identifier).optional(),
|
|
58
|
+
relatedColumns: z.record(identifier, z.strictObject({ via: identifier, field: identifier })).optional(),
|
|
59
|
+
compact: z.boolean().optional(), mobileCards: z.boolean().optional(),
|
|
60
|
+
defaultSort: z.strictObject({ key: identifier, direction: z.enum(['asc', 'desc']) }).optional(),
|
|
61
|
+
pageSize: z.union([z.literal(10), z.literal(20), z.literal(30), z.literal(50), z.literal(100)]).optional(),
|
|
62
|
+
search: z.array(identifier).optional(),
|
|
63
|
+
filter: z.record(identifier, z.union([z.literal(false), filterKind])).optional(),
|
|
64
|
+
views: z.array(z.strictObject({ id: identifier, label: z.string().min(1), where: z.record(z.string(), z.unknown()), default: z.boolean().optional() })).optional(),
|
|
65
|
+
sort: z.record(identifier, z.union([z.literal(false), z.strictObject({ fields: z.array(identifier).min(1).max(4) })])).optional(),
|
|
66
|
+
})
|
|
67
|
+
const schema = z.object({
|
|
68
|
+
plugins: z.array(z.custom<WorkbasePlugin>()).readonly().optional(),
|
|
69
|
+
interactive: z.boolean().optional(),
|
|
70
|
+
ui: z.strictObject({
|
|
71
|
+
defaultLanguage: z.enum(['en', 'cs']).optional(),
|
|
72
|
+
entities: z.record(identifier, z.strictObject({ views: calendarViewsSchema.optional(), form: formDisplaySchema.optional(), sections: formSectionsSchema.optional(), list: listHints.optional(), lookup: z.boolean().optional(),
|
|
73
|
+
detail: detailDisplaySchema.optional(),
|
|
74
|
+
})),
|
|
75
|
+
navigation: z.strictObject({
|
|
76
|
+
// Route IDs are their staticData.title keys; overrides remain presentation only.
|
|
77
|
+
routes: z.array(z.strictObject({ id: z.string().min(1), icon: navigationIconSchema.optional(), order: z.number().int().optional() })).optional(),
|
|
78
|
+
groups: z.array(z.strictObject({ id: identifier, label: z.string().min(1), icon: navigationIconSchema.optional(), order: z.number().int().optional() })),
|
|
79
|
+
items: z.array(z.strictObject({ id: identifier, entity: identifier, label: z.string().min(1).optional(), icon: navigationIconSchema.optional(), group: identifier.optional(), order: z.number().int().optional(), roles: z.array(identifier).min(1).optional(), view: identifier.optional(), hidden: z.boolean().optional() })),
|
|
80
|
+
}).optional(),
|
|
81
|
+
}).optional(),
|
|
82
|
+
pluginConfig: z.record(z.string(), z.unknown()).optional(),
|
|
83
|
+
locale: z.enum(['en', 'cs']).default('en'),
|
|
84
|
+
timeZone: z.string().default('UTC'),
|
|
85
|
+
enumLabels: z.record(z.string(), z.record(z.string(), z.string())).optional(),
|
|
86
|
+
registration: z.enum(['open', 'invite-only']).default('open'),
|
|
87
|
+
organizationOwnerRole: identifier.default('owner'),
|
|
88
|
+
displayName: z.string().trim().min(1).optional(),
|
|
89
|
+
id: identifier, revision: z.number().int().positive(),
|
|
90
|
+
entities: z.record(identifier, z.object({
|
|
91
|
+
fields: z.record(identifier, fieldSchema),
|
|
92
|
+
relations: z.record(identifier, z.object({ field: identifier, entity: identifier, many: z.boolean().optional(), through: z.strictObject({ entity: identifier, field: identifier, createCommand: z.string().min(1), deleteCommand: z.string().min(1) }).optional() })).default({}),
|
|
93
|
+
commandsOnly: z.boolean().optional(),
|
|
94
|
+
displayField: identifier.optional(),
|
|
95
|
+
// Trusted server AST. displayField is the projected result key, not a stored label.
|
|
96
|
+
label: z.union([
|
|
97
|
+
z.custom<ISequelizable & ISerializable>(value => !!value && typeof (value as ISequelizable).toSQL === 'function' && typeof (value as ISerializable).serialize === 'function'),
|
|
98
|
+
z.string().transform(value => Q.expr(value)),
|
|
99
|
+
]).optional(),
|
|
100
|
+
checks: z.array(z.object({ left: identifier, op: z.enum(['<=', '>=']), right: identifier })).default([]),
|
|
101
|
+
})),
|
|
102
|
+
roles: z.array(identifier).min(1),
|
|
103
|
+
account: z.object({ entity: identifier, managedBy: z.array(identifier).optional(), assignments: z.array(identifier).optional() }).optional(),
|
|
104
|
+
policies: z.record(identifier, z.record(identifier, z.union([z.literal('all'), z.literal('none'), z.strictObject({ where: z.record(z.string(), z.unknown()), deny: z.enum(['empty', 'forbidden']).optional(), fields: z.array(identifier).optional() })]))).default({}),
|
|
105
|
+
permissions: z.record(z.string(), z.record(identifier, operations)),
|
|
106
|
+
commands: z.array(z.string()).default([]),
|
|
107
|
+
organizationPermissions: z.record(z.string(), z.array(z.enum(organizationActions))).optional().transform(value => value ?? {}),
|
|
108
|
+
}).superRefine((config, ctx) => {
|
|
109
|
+
if (config.plugins?.length && typeof config.interactive !== 'boolean') ctx.addIssue({ code: 'custom', path: ['interactive'], message: 'interactive must be an explicit boolean when plugins are installed' })
|
|
110
|
+
})
|
|
111
|
+
export type Field = z.infer<typeof fieldSchema>
|
|
112
|
+
export type InstanceConfig = z.infer<typeof schema>
|
|
113
|
+
export type InstanceInput = z.input<typeof schema>
|
|
114
|
+
export type Operation = 'read' | 'create' | 'update' | 'delete'
|
|
115
|
+
export const baseFields = ['id', 'organization_id', 'created_at', 'updated_at', 'version']
|
|
116
|
+
const reserved = new Set(['users', 'organizations', 'memberships', 'sessions', 'invitations', 'email_outbox', 'audit_outbox', 'security_log', 'idempotency_keys', 'instance_meta', 'webhook_deliveries', 'audit_events', 'd1_migrations', 'identities', 'access_tokens', 'user', 'session', 'account', 'verification', 'rateLimit', 'identity_link_grants', '_plugin_migrations'])
|
|
117
|
+
export function defineInstance(input: Omit<ShorthandInput, 'roles' | 'entities' | 'permissions'> & { roles?: string[]; entities?: ShorthandInput['entities']; permissions?: ShorthandInput['permissions'] }): InstanceConfig {
|
|
118
|
+
const resolved = resolvePlugins(input.plugins ?? [], input.interactive)
|
|
119
|
+
const pluginConfig = { ...input.pluginConfig }
|
|
120
|
+
let contribution: Partial<InstanceInput> = {}
|
|
121
|
+
const model: Partial<InstanceInput> = {}
|
|
122
|
+
for (const plugin of resolved.plugins) {
|
|
123
|
+
for (const key of Object.keys(plugin.model ?? {}) as (keyof NonNullable<WorkbasePlugin['model']>)[]) {
|
|
124
|
+
if (!['entities', 'permissions', 'policies', 'ui', 'account', 'commands', 'organizationPermissions'].includes(key)) throw new Error(`Invalid plugin model contribution: ${key}`)
|
|
125
|
+
if (Object.hasOwn(model, key)) throw new Error(`Duplicate plugin model contribution: ${key}`)
|
|
126
|
+
Object.assign(model, { [key]: plugin.model![key] })
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
for (const plugin of resolved.plugins) {
|
|
130
|
+
if (plugin.configure) contribution = { ...contribution, ...plugin.configure(plugin.configSchema?.parse(pluginConfig[plugin.name])) }
|
|
131
|
+
}
|
|
132
|
+
const config = schema.parse(expand({ ...model, ...input, entities: input.entities ?? model.entities ?? {}, permissions: input.permissions ?? model.permissions ?? {}, ...contribution, roles: contribution.roles ?? input.roles ?? [],
|
|
133
|
+
organizationPermissions: { ...model.organizationPermissions, ...contribution.organizationPermissions, ...input.organizationPermissions },
|
|
134
|
+
...(input.pluginConfig || Object.keys(pluginConfig).length ? { pluginConfig } : {}),
|
|
135
|
+
}))
|
|
136
|
+
for (const name of Object.keys(config.pluginConfig ?? {})) {
|
|
137
|
+
if (!config.plugins?.some(plugin => plugin.name === name)) throw new Error(`Unknown plugin config: ${name}`)
|
|
138
|
+
}
|
|
139
|
+
// Custom roles have no default grants. Preserve sparse explicit/model tables;
|
|
140
|
+
// implicit tables retain their existing empty entries for custom roles.
|
|
141
|
+
const defaultRoles = input.organizationPermissions === undefined && model.organizationPermissions === undefined
|
|
142
|
+
? config.roles : config.roles.filter(role => Object.hasOwn(defaultOrganizationPermissions, role))
|
|
143
|
+
config.organizationPermissions = { ...Object.fromEntries(defaultRoles.map(role => [role, [...(defaultOrganizationPermissions[role] ?? [])]])), ...config.organizationPermissions }
|
|
144
|
+
if (config.organizationOwnerRole !== 'owner' && !config.roles.includes(config.organizationOwnerRole)) throw new Error('Unknown organization owner role')
|
|
145
|
+
for (const [name, entity] of Object.entries(config.entities)) {
|
|
146
|
+
if ((reserved.has(name) && !(name === 'users' && config.account?.entity === name)) || name === 'atomic_assert' || name.startsWith('sqlite_') || name.startsWith('d1_')) throw new Error(`Reserved entity: ${name}`)
|
|
147
|
+
if (Object.keys(entity.fields).length > 90) throw new Error('Entity exceeds the supported field/parameter budget')
|
|
148
|
+
for (const [key, field] of Object.entries(entity.fields)) {
|
|
149
|
+
if (name === 'users' && ['email', 'password_hash', 'salt'].includes(key)) throw new Error(`Account identity field is private: ${key}`)
|
|
150
|
+
if (baseFields.includes(key)) throw new Error(`Reserved field: ${key}`)
|
|
151
|
+
if (field.min !== undefined && !['int', 'float'].includes(field.type)) throw new Error('min requires a numeric field')
|
|
152
|
+
if (field.default !== undefined && field.default !== null) {
|
|
153
|
+
const value = field.default
|
|
154
|
+
const valid = field.type === 'bool' ? typeof value === 'boolean'
|
|
155
|
+
: field.type === 'int' ? Number.isSafeInteger(value) && (value as number) >= (field.min ?? Number.MIN_SAFE_INTEGER)
|
|
156
|
+
: field.type === 'float' ? typeof value === 'number' && Number.isFinite(value) && value >= (field.min ?? -Number.MAX_VALUE)
|
|
157
|
+
: field.type === 'enum' ? field.values!.includes(String(value)) && typeof value === 'string'
|
|
158
|
+
: field.type === 'datetime' ? typeof value === 'string' && z.iso.datetime().safeParse(value).success
|
|
159
|
+
: typeof value === 'string'
|
|
160
|
+
if (!valid) throw new Error(`Invalid default: ${name}.${key}`)
|
|
161
|
+
}
|
|
162
|
+
if (field.required && field.default === null) throw new Error(`Required default cannot be null: ${name}.${key}`)
|
|
163
|
+
if (field.type === 'ref' && !Object.hasOwn(config.entities, field.entity!)) throw new Error(`Unknown reference: ${field.entity}`)
|
|
164
|
+
if (field.backfillFrom) {
|
|
165
|
+
const ref = entity.fields[field.backfillFrom.refField]
|
|
166
|
+
if (!ref?.entity || !config.entities[ref.entity]?.fields[field.backfillFrom.valueField]) throw new Error('Invalid backfill reference')
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
for (const [relationName, r] of Object.entries(entity.relations)) {
|
|
170
|
+
const target = r.many ? config.entities[r.entity]?.fields[r.field] : entity.fields[r.field]
|
|
171
|
+
if (!target || target.type !== 'ref' || target.entity !== (r.many ? name : r.entity)) throw new Error(`Invalid relation on ${name}`)
|
|
172
|
+
if (r.through) {
|
|
173
|
+
const join = config.entities[r.entity]
|
|
174
|
+
const other = join?.fields[r.through.field]
|
|
175
|
+
if (Object.hasOwn(entity.fields, relationName) || !r.many || r.field === r.through.field || other?.type !== 'ref' || other.entity !== r.through.entity
|
|
176
|
+
|| Object.entries(join.fields).some(([field, spec]) => ![r.field, r.through!.field].includes(field) && !(spec.readOnly && spec.ui?.hidden))
|
|
177
|
+
|| ![r.through.createCommand, r.through.deleteCommand].every(command => config.commands.includes(command))) throw new Error(`Invalid pure join relation on ${name}`)
|
|
178
|
+
const inverse = Object.values(config.entities[r.through.entity]?.relations ?? {}).some(inverse => inverse.entity === r.entity && inverse.field === r.through!.field && inverse.through?.entity === name && inverse.through.field === r.field)
|
|
179
|
+
if (!inverse) throw new Error(`Missing inverse pure join relation on ${name}`)
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
for (const c of entity.checks) if (!entity.fields[c.left] || !entity.fields[c.right]) throw new Error('Unknown check field')
|
|
183
|
+
}
|
|
184
|
+
for (const [role, grants] of Object.entries(config.permissions)) {
|
|
185
|
+
if (!config.roles.includes(role as any)) throw new Error(`Unknown role ${role}`)
|
|
186
|
+
for (const name of Object.keys(grants)) if (!Object.hasOwn(config.entities, name)) throw new Error(`Unknown grant entity ${name}`)
|
|
187
|
+
}
|
|
188
|
+
for (const role of Object.keys(config.organizationPermissions)) {
|
|
189
|
+
if (!config.roles.includes(role as any)) throw new Error(`Unknown organization role ${role}`)
|
|
190
|
+
}
|
|
191
|
+
if (config.account) {
|
|
192
|
+
const account = config.entities[config.account.entity]
|
|
193
|
+
if (!account) throw new Error('Unknown account entity')
|
|
194
|
+
for (const role of config.account.managedBy ?? []) if (!config.roles.includes(role)) throw new Error(`Unknown account manager role: ${role}`)
|
|
195
|
+
for (const field of config.account.assignments ?? []) if (!Object.hasOwn(account.fields, field)) throw new Error(`Unknown account assignment field: ${field}`)
|
|
196
|
+
}
|
|
197
|
+
for (const [name, entity] of Object.entries(config.entities)) if (entity.displayField && ![...baseFields, ...Object.keys(entity.fields)].includes(entity.displayField)) throw new Error(`Unknown displayField: ${name}`)
|
|
198
|
+
// Presentation hints are validated at load; readable capabilities further narrow them at runtime.
|
|
199
|
+
const navigation = config.ui?.navigation
|
|
200
|
+
if (navigation) {
|
|
201
|
+
const groups = navigation.groups.map(group => group.id)
|
|
202
|
+
if (new Set(groups).size !== groups.length) throw new Error('Duplicate navigation group')
|
|
203
|
+
const items = navigation.items.map(item => item.id)
|
|
204
|
+
if (new Set(items).size !== items.length) throw new Error('Duplicate navigation item')
|
|
205
|
+
for (const item of navigation.items) {
|
|
206
|
+
if (!Object.hasOwn(config.entities, item.entity)) throw new Error(`Unknown navigation entity: ${item.entity}`)
|
|
207
|
+
if (item.group && !groups.includes(item.group)) throw new Error(`Unknown navigation group: ${item.group}`)
|
|
208
|
+
for (const role of item.roles ?? []) if (!config.roles.includes(role)) throw new Error(`Unknown navigation role: ${role}`)
|
|
209
|
+
if (item.view && !config.ui?.entities[item.entity]?.list?.views?.some(view => view.id === item.view)) throw new Error(`Unknown navigation view: ${item.entity}.${item.view}`)
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
for (const [name, hints] of Object.entries(config.ui?.entities ?? {})) {
|
|
213
|
+
const entity = config.entities[name]
|
|
214
|
+
if (!entity) throw new Error(`Unknown UI entity: ${name}`)
|
|
215
|
+
const known = (field: string) => baseFields.includes(field) || Object.hasOwn(entity.fields, field)
|
|
216
|
+
validateFormDisplay(name, entity, hints)
|
|
217
|
+
if (hints.detail) validateDetailDisplay(config, name, hints.detail)
|
|
218
|
+
for (const [field, spec] of Object.entries(entity.fields)) if (spec.ui?.signedBy && (!known(spec.ui.signedBy.field) || !['int', 'float'].includes(spec.type))) throw new Error(`Invalid signed UI field: ${name}.${field}`)
|
|
219
|
+
validateCalendarViews(config, name, hints.views)
|
|
220
|
+
const list = hints.list
|
|
221
|
+
if (!list) continue
|
|
222
|
+
const scalar = (field: string) => known(field) && entity.fields[field]?.type !== 'ref'
|
|
223
|
+
for (const [key, column] of Object.entries(list.relatedColumns ?? {})) {
|
|
224
|
+
const via = entity.fields[column.via]
|
|
225
|
+
const target = via?.type === 'ref' && via.entity ? config.entities[via.entity] : undefined
|
|
226
|
+
const field = target?.fields[column.field]
|
|
227
|
+
if (known(key) || !field || field.type !== 'ref' || !field.entity) throw new Error(`Invalid UI related column: ${name}.${key}`)
|
|
228
|
+
}
|
|
229
|
+
for (const field of [...(list.columns ?? []).filter(field => !list.relatedColumns?.[field]), ...(list.search ?? []), ...Object.keys(list.sort ?? {}), ...Object.keys(list.filter ?? {})]) if (!known(field)) throw new Error(`Unknown UI field: ${name}.${field}`)
|
|
230
|
+
for (const field of list.search ?? []) if (!['string', 'text'].includes(entity.fields[field]?.type ?? (field === 'id' ? 'string' : ''))) throw new Error(`Invalid UI search field: ${name}.${field}`)
|
|
231
|
+
for (const [key, hint] of Object.entries(list.sort ?? {})) if (hint) {
|
|
232
|
+
if (new Set(hint.fields).size !== hint.fields.length) throw new Error(`Duplicate UI sort field: ${name}.${key}`)
|
|
233
|
+
if (!scalar(key) || !hint.fields.every(scalar)) throw new Error(`Invalid UI sort fields: ${name}`)
|
|
234
|
+
}
|
|
235
|
+
const kindFor = (field: string) => ({ string: 'text', text: 'text', ref: 'relation', enum: 'enum', bool: 'boolean', int: 'number', float: 'number', datetime: 'date' } as Record<string, string>)[entity.fields[field]?.type ?? (field === 'version' ? 'int' : ['created_at', 'updated_at'].includes(field) ? 'datetime' : 'string')]
|
|
236
|
+
for (const [field, kind] of Object.entries(list.filter ?? {})) if (kind && kind !== kindFor(field)) throw new Error(`Invalid UI filter kind: ${name}.${field}`)
|
|
237
|
+
const ids = (list.views ?? []).map(view => view.id)
|
|
238
|
+
if (ids.includes('all')) throw new Error(`Reserved UI view id: ${name}.all`)
|
|
239
|
+
if (new Set(ids).size !== ids.length) throw new Error(`Duplicate UI view id: ${name}`)
|
|
240
|
+
if ((list.views ?? []).filter(view => view.default).length > 1) throw new Error(`Multiple default UI views: ${name}`)
|
|
241
|
+
for (const view of list.views ?? []) if (!filterSchema(config)(name, 0).safeParse(view.where).success) throw new Error(`Invalid UI view where: ${name}.${view.id}`)
|
|
242
|
+
if (list.defaultSort && (!scalar(list.defaultSort.key) || list.sort?.[list.defaultSort.key] === false || (['enum', 'text'].includes(entity.fields[list.defaultSort.key]?.type) && !list.sort?.[list.defaultSort.key]))) throw new Error(`Invalid UI default sort: ${name}`)
|
|
243
|
+
}
|
|
244
|
+
validateLabelExpressions(config)
|
|
245
|
+
validatePolicies(config)
|
|
246
|
+
return config
|
|
247
|
+
}
|
|
248
|
+
export function bodyValidator(entity: InstanceConfig['entities'][string], partial = false) {
|
|
249
|
+
const shape: Record<string, z.ZodType> = {}
|
|
250
|
+
for (const [name, f] of Object.entries(entity.fields)) {
|
|
251
|
+
if (f.readOnly) continue
|
|
252
|
+
let v: z.ZodType
|
|
253
|
+
switch (f.type) {
|
|
254
|
+
case 'int': v = z.number().int().min(f.min ?? Number.MIN_SAFE_INTEGER); break
|
|
255
|
+
case 'float': v = z.number().min(f.min ?? -Number.MAX_VALUE); break
|
|
256
|
+
case 'bool': v = z.boolean(); break
|
|
257
|
+
case 'datetime': v = z.iso.datetime(); break
|
|
258
|
+
case 'enum': v = z.enum(f.values as [string, ...string[]]); break
|
|
259
|
+
default: v = z.string().min(1).max(f.type === 'text' ? 100000 : 2000)
|
|
260
|
+
}
|
|
261
|
+
if (!f.required) v = v.nullable()
|
|
262
|
+
if (!partial && f.default !== undefined) v = v.default(f.default)
|
|
263
|
+
else if (partial || !f.required) v = v.optional()
|
|
264
|
+
shape[name] = v
|
|
265
|
+
}
|
|
266
|
+
return z.strictObject(shape)
|
|
267
|
+
}
|
|
268
|
+
export const allowed = (c: InstanceConfig, role: string, entity: string, op: Operation) => Object.hasOwn(c.permissions, role) && Object.hasOwn(c.permissions[role], entity) && c.permissions[role][entity].includes(op)
|
|
269
|
+
|
|
270
|
+
/** Clone mutable schema/config data while retaining the trusted plugin code references. */
|
|
271
|
+
export function cloneInstanceConfig(config: InstanceConfig): InstanceConfig {
|
|
272
|
+
const { plugins, ...data } = config
|
|
273
|
+
// AST instances carry prototypes; structuredClone would erase their renderers.
|
|
274
|
+
const labels = Object.fromEntries(Object.entries(data.entities).flatMap(([name, entity]) => entity.label ? [[name, entity.label]] : []))
|
|
275
|
+
const plain = { ...data, entities: Object.fromEntries(Object.entries(data.entities).map(([name, { label: _label, ...entity }]) => [name, entity])) }
|
|
276
|
+
const cloned = structuredClone(plain) as InstanceConfig
|
|
277
|
+
for (const [name, label] of Object.entries(labels)) cloned.entities[name].label = label
|
|
278
|
+
return { ...cloned, ...(plugins ? { plugins } : {}) }
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** JSON-backed config tools store the library's expression format, never JS AST internals. */
|
|
282
|
+
export function serializableInstanceConfig(config: InstanceConfig) {
|
|
283
|
+
return { ...config, entities: Object.fromEntries(Object.entries(config.entities).map(([name, entity]) => [name, {
|
|
284
|
+
...entity, ...(entity.label ? { label: entity.label.serialize() } : {}),
|
|
285
|
+
}])) }
|
|
286
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
export type ConsoleGrant = string | { entity: string; operation?: 'read' | 'create' | 'update' | 'delete' }
|
|
2
|
+
export interface ConsoleGroup { id: string; label: string; order?: number; icon?: string }
|
|
3
|
+
export interface ConsoleNavigation {
|
|
4
|
+
id: string
|
|
5
|
+
placement: 'sidebar' | 'settings'
|
|
6
|
+
label: string
|
|
7
|
+
icon?: string
|
|
8
|
+
order?: number
|
|
9
|
+
group?: ConsoleGroup
|
|
10
|
+
grant?: ConsoleGrant
|
|
11
|
+
roles?: readonly string[]
|
|
12
|
+
/** Exactly one destination; entity views reuse the generated entity route. */
|
|
13
|
+
page?: string
|
|
14
|
+
entity?: string
|
|
15
|
+
view?: string
|
|
16
|
+
}
|
|
17
|
+
export type ConsoleAggregate = { fn: 'count' } | { fn: 'sum'; field: string }
|
|
18
|
+
export type ConsoleWidget = { id: string; label: string } & (
|
|
19
|
+
| { kind: 'stat'; query: Pick<ConsoleQuery, 'entity' | 'where'>; aggregate: ConsoleAggregate }
|
|
20
|
+
| { kind: 'table'; query: ConsoleQuery; columns: string[] }
|
|
21
|
+
| { kind: 'list'; query: ConsoleQuery; field: string })
|
|
22
|
+
/** The SR-74 row hint, referencing widget IDs instead of detail card keys. */
|
|
23
|
+
export type ConsoleWidgetSection = Extract<ConsoleDetailSection, { row: string[] }>
|
|
24
|
+
export type ConsoleWidgetResult = Pick<ConsoleWidget, 'id' | 'label'> & (
|
|
25
|
+
| { kind: 'stat'; value: number | null }
|
|
26
|
+
| { kind: 'table'; columns: string[]; data: Record<string, unknown>[] }
|
|
27
|
+
| { kind: 'list'; field: string; data: Record<string, unknown>[] })
|
|
28
|
+
export interface ConsolePageResult {
|
|
29
|
+
id: string; label: string; sections?: ConsoleWidgetSection[]; widgets: ConsoleWidgetResult[]
|
|
30
|
+
}
|
|
31
|
+
export interface ConsolePage {
|
|
32
|
+
id: string
|
|
33
|
+
label: string
|
|
34
|
+
/** Organization-relative path; renderer IDs are resolved by the shell. */
|
|
35
|
+
path: string
|
|
36
|
+
grant?: ConsoleGrant
|
|
37
|
+
renderer?: string
|
|
38
|
+
widgets?: readonly ConsoleWidget[]
|
|
39
|
+
sections?: ConsoleWidgetSection[]
|
|
40
|
+
}
|
|
41
|
+
/** Wire types only: canonical model validation remains in core. No runtime imports. */
|
|
42
|
+
export interface ConsoleQuery {
|
|
43
|
+
entity: string; select: string[]; where?: Record<string, unknown>; limit: number
|
|
44
|
+
labels?: string[]
|
|
45
|
+
orderBy?: { field: string; dir: 'asc' | 'desc'; label?: boolean }[]
|
|
46
|
+
}
|
|
47
|
+
export interface ConsoleFieldDisplay {
|
|
48
|
+
hidden?: boolean; kind?: 'input' | 'textarea' | 'select' | 'boolean' | 'number' | 'date' | 'datetime' | 'time' | 'colour'
|
|
49
|
+
span?: 'half' | 'full'; section?: string; signedBy?: { field: string; negativeValue: string }
|
|
50
|
+
}
|
|
51
|
+
/** Bounded card rows, not a component tree. `info` denotes the record information card. */
|
|
52
|
+
export type ConsoleDetailSection = { fields: 'info'; row?: never } | { row: string[]; fields?: never }
|
|
53
|
+
export type ConsoleDetailItem = string | { field: string; label?: string; help?: string; when?: { field: string; eq: string | number | boolean | null } }
|
|
54
|
+
/** A reusable entity list bound to the current record identity. UI hints grant no authority. */
|
|
55
|
+
export interface ConsoleContextList {
|
|
56
|
+
entity: string; label: string; bind: { field: string; record: 'id' }
|
|
57
|
+
columns?: string[]; create?: boolean
|
|
58
|
+
}
|
|
59
|
+
export interface ConsoleCalendarView { kind: 'calendar'; startField: string; endField?: string; titleField?: string; titleFields?: string[]; secondaryField?: string }
|
|
60
|
+
export interface ConsoleEntityDisplay {
|
|
61
|
+
views?: ConsoleCalendarView[]
|
|
62
|
+
lookup?: boolean
|
|
63
|
+
list?: {
|
|
64
|
+
columns?: string[]; search?: string[]; pageSize?: 10 | 20 | 30 | 50 | 100; compact?: boolean; mobileCards?: boolean
|
|
65
|
+
relatedColumns?: Record<string, { via: string; field: string }>
|
|
66
|
+
defaultSort?: { key: string; direction: 'asc' | 'desc' }
|
|
67
|
+
filter?: Record<string, false | 'text' | 'enum' | 'relation' | 'number' | 'date' | 'boolean'>
|
|
68
|
+
sort?: Record<string, false | { fields: string[] }>
|
|
69
|
+
views?: { id: string; label: string; where: Record<string, unknown>; default?: boolean }[]
|
|
70
|
+
}
|
|
71
|
+
detail?: {
|
|
72
|
+
/** Explicit field saves; eligibility still follows the edit form and live grants. */
|
|
73
|
+
inlineEdit?: boolean
|
|
74
|
+
lists?: Record<string, ConsoleContextList>
|
|
75
|
+
summary?: ConsoleDetailItem[]
|
|
76
|
+
groups?: { id: string; label: string; help?: string; fields: ConsoleDetailItem[] }[]
|
|
77
|
+
sections?: ConsoleDetailSection[]
|
|
78
|
+
fields?: string[]; metrics?: { field: string; unitField?: string; tone?: 'positive' | 'negative' }[]
|
|
79
|
+
relations?: Record<string, { columns: string[]; defaultSort?: { key: string; direction: 'asc' | 'desc' } }>
|
|
80
|
+
}
|
|
81
|
+
fields?: Record<string, ConsoleFieldDisplay>
|
|
82
|
+
form?: { create?: { fields: string[] }; edit?: { fields: string[] } }
|
|
83
|
+
sections?: { id: string; label: string; fields: string[] }[]
|
|
84
|
+
}
|
|
85
|
+
export interface ConsoleModelUI {
|
|
86
|
+
defaultLanguage?: 'en' | 'cs'
|
|
87
|
+
entities?: Record<string, ConsoleEntityDisplay>
|
|
88
|
+
navigation?: {
|
|
89
|
+
routes?: { id: string; icon?: string; order?: number }[]
|
|
90
|
+
groups: ConsoleGroup[]
|
|
91
|
+
items: { id: string; entity: string; label?: string; icon?: string; group?: string; order?: number; roles?: string[]; view?: string; hidden?: boolean }[]
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
export interface ConsoleContribution {
|
|
95
|
+
navigation?: readonly ConsoleNavigation[]
|
|
96
|
+
pages?: readonly ConsolePage[]
|
|
97
|
+
entities?: Readonly<Record<string, ConsoleEntityDisplay>>
|
|
98
|
+
}
|
|
99
|
+
export interface ConsoleRegistry {
|
|
100
|
+
navigation: ConsoleNavigation[]
|
|
101
|
+
pages: ConsolePage[]
|
|
102
|
+
entities: Record<string, ConsoleEntityDisplay>
|
|
103
|
+
/** Existing model.ui transported verbatim; presentation hints grant no authority. */
|
|
104
|
+
modelUi?: ConsoleModelUI
|
|
105
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { ConsoleContribution } from './console-contract'
|
|
2
|
+
|
|
3
|
+
/** Execution and its built-in administration remain owned by core (ADR 0002). */
|
|
4
|
+
export const coreConsoleContribution: ConsoleContribution = {
|
|
5
|
+
pages: [{ id: 'core.overview', path: '/', label: 'overview', renderer: 'core.overview' }, { id: 'core.workflows', path: '/settings/workflows', label: 'workflowRuns', grant: 'workflows.read', renderer: 'core.workflows' }],
|
|
6
|
+
navigation: [{ id: 'core.overview', placement: 'sidebar', page: 'core.overview', label: 'overview', icon: 'LayoutDashboard', order: 0 }, { id: 'core.workflows', placement: 'settings', page: 'core.workflows', label: 'workflowRuns', icon: 'Workflow', order: 50, group: { id: 'operations', label: 'settingsOperations', order: 100 }, grant: 'workflows.read' }],
|
|
7
|
+
}
|