@stonecrop/stonecrop 0.30.0 → 0.32.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 (121) hide show
  1. package/dist/stonecrop.js +3548 -2740
  2. package/dist/stonecrop.js.map +1 -1
  3. package/dist/tsdoc-metadata.json +1 -1
  4. package/package.json +33 -27
  5. package/dist/src/client-action.d.ts +0 -31
  6. package/dist/src/client-action.d.ts.map +0 -1
  7. package/dist/src/client-action.js +0 -169
  8. package/dist/src/client-handler.d.ts +0 -43
  9. package/dist/src/client-handler.d.ts.map +0 -1
  10. package/dist/src/client-handler.js +0 -42
  11. package/dist/src/composables/lazy-link.d.ts +0 -25
  12. package/dist/src/composables/lazy-link.d.ts.map +0 -1
  13. package/dist/src/composables/lazy-link.js +0 -124
  14. package/dist/src/composables/operation-log.d.ts +0 -136
  15. package/dist/src/composables/operation-log.d.ts.map +0 -1
  16. package/dist/src/composables/operation-log.js +0 -224
  17. package/dist/src/composables/stonecrop.d.ts +0 -37
  18. package/dist/src/composables/stonecrop.d.ts.map +0 -1
  19. package/dist/src/composables/stonecrop.js +0 -433
  20. package/dist/src/doctype.d.ts +0 -243
  21. package/dist/src/doctype.d.ts.map +0 -1
  22. package/dist/src/doctype.js +0 -325
  23. package/dist/src/draft.d.ts +0 -35
  24. package/dist/src/draft.d.ts.map +0 -1
  25. package/dist/src/draft.js +0 -36
  26. package/dist/src/exceptions.d.ts +0 -14
  27. package/dist/src/exceptions.d.ts.map +0 -1
  28. package/dist/src/exceptions.js +0 -16
  29. package/dist/src/field-triggers.d.ts +0 -184
  30. package/dist/src/field-triggers.d.ts.map +0 -1
  31. package/dist/src/field-triggers.js +0 -577
  32. package/dist/src/index.d.ts +0 -25
  33. package/dist/src/index.d.ts.map +0 -1
  34. package/dist/src/index.js +0 -39
  35. package/dist/src/plugins/index.d.ts +0 -35
  36. package/dist/src/plugins/index.d.ts.map +0 -1
  37. package/dist/src/plugins/index.js +0 -98
  38. package/dist/src/registry.d.ts +0 -161
  39. package/dist/src/registry.d.ts.map +0 -1
  40. package/dist/src/registry.js +0 -384
  41. package/dist/src/schema-validator.d.ts +0 -78
  42. package/dist/src/schema-validator.d.ts.map +0 -1
  43. package/dist/src/schema-validator.js +0 -398
  44. package/dist/src/stonecrop.d.ts +0 -539
  45. package/dist/src/stonecrop.d.ts.map +0 -1
  46. package/dist/src/stonecrop.js +0 -610
  47. package/dist/src/stores/hst.d.ts +0 -92
  48. package/dist/src/stores/hst.d.ts.map +0 -1
  49. package/dist/src/stores/hst.js +0 -487
  50. package/dist/src/stores/index.d.ts +0 -9
  51. package/dist/src/stores/index.d.ts.map +0 -1
  52. package/dist/src/stores/index.js +0 -13
  53. package/dist/src/stores/operation-log.d.ts +0 -262
  54. package/dist/src/stores/operation-log.d.ts.map +0 -1
  55. package/dist/src/stores/operation-log.js +0 -571
  56. package/dist/src/stores/validation.d.ts +0 -83
  57. package/dist/src/stores/validation.d.ts.map +0 -1
  58. package/dist/src/stores/validation.js +0 -104
  59. package/dist/src/types/client-action.d.ts +0 -121
  60. package/dist/src/types/client-action.d.ts.map +0 -1
  61. package/dist/src/types/client-action.js +0 -0
  62. package/dist/src/types/composable.d.ts +0 -268
  63. package/dist/src/types/composable.d.ts.map +0 -1
  64. package/dist/src/types/composable.js +0 -0
  65. package/dist/src/types/doctype.d.ts +0 -34
  66. package/dist/src/types/doctype.d.ts.map +0 -1
  67. package/dist/src/types/doctype.js +0 -0
  68. package/dist/src/types/field-triggers.d.ts +0 -186
  69. package/dist/src/types/field-triggers.d.ts.map +0 -1
  70. package/dist/src/types/field-triggers.js +0 -4
  71. package/dist/src/types/hst.d.ts +0 -70
  72. package/dist/src/types/hst.d.ts.map +0 -1
  73. package/dist/src/types/hst.js +0 -0
  74. package/dist/src/types/index.d.ts +0 -11
  75. package/dist/src/types/index.d.ts.map +0 -1
  76. package/dist/src/types/index.js +0 -11
  77. package/dist/src/types/operation-log.d.ts +0 -163
  78. package/dist/src/types/operation-log.d.ts.map +0 -1
  79. package/dist/src/types/operation-log.js +0 -0
  80. package/dist/src/types/plugin.d.ts +0 -37
  81. package/dist/src/types/plugin.d.ts.map +0 -1
  82. package/dist/src/types/plugin.js +0 -0
  83. package/dist/src/types/registry.d.ts +0 -11
  84. package/dist/src/types/registry.d.ts.map +0 -1
  85. package/dist/src/types/registry.js +0 -0
  86. package/dist/src/types/schema-validator.d.ts +0 -66
  87. package/dist/src/types/schema-validator.d.ts.map +0 -1
  88. package/dist/src/types/schema-validator.js +0 -13
  89. package/dist/src/types/stonecrop.d.ts +0 -32
  90. package/dist/src/types/stonecrop.d.ts.map +0 -1
  91. package/dist/src/types/stonecrop.js +0 -0
  92. package/dist/stonecrop.tsbuildinfo +0 -1
  93. package/src/client-action.ts +0 -207
  94. package/src/client-handler.ts +0 -55
  95. package/src/composables/lazy-link.ts +0 -145
  96. package/src/composables/operation-log.ts +0 -257
  97. package/src/composables/stonecrop.ts +0 -556
  98. package/src/doctype.ts +0 -360
  99. package/src/draft.ts +0 -38
  100. package/src/exceptions.ts +0 -16
  101. package/src/field-triggers.ts +0 -686
  102. package/src/index.ts +0 -81
  103. package/src/plugins/index.ts +0 -113
  104. package/src/registry.ts +0 -433
  105. package/src/schema-validator.ts +0 -476
  106. package/src/stonecrop.ts +0 -721
  107. package/src/stores/hst.ts +0 -626
  108. package/src/stores/index.ts +0 -21
  109. package/src/stores/operation-log.ts +0 -675
  110. package/src/stores/validation.ts +0 -138
  111. package/src/types/client-action.ts +0 -121
  112. package/src/types/composable.ts +0 -288
  113. package/src/types/doctype.ts +0 -35
  114. package/src/types/field-triggers.ts +0 -201
  115. package/src/types/hst.ts +0 -77
  116. package/src/types/index.ts +0 -11
  117. package/src/types/operation-log.ts +0 -202
  118. package/src/types/plugin.ts +0 -38
  119. package/src/types/registry.ts +0 -10
  120. package/src/types/schema-validator.ts +0 -69
  121. package/src/types/stonecrop.ts +0 -33
package/src/index.ts DELETED
@@ -1,81 +0,0 @@
1
- export type * from '@stonecrop/aform/types'
2
- export type * from '@stonecrop/atable/types'
3
-
4
- import { useClientAction } from './client-action'
5
- import { executeClientHandler } from './client-handler'
6
- import { useLazyLink } from './composables/lazy-link'
7
- import { useStonecrop } from './composables/stonecrop'
8
- import { useOperationLog, useUndoRedoShortcuts, withBatch } from './composables/operation-log'
9
- import Doctype from './doctype'
10
- import { DRAFT_RECORD_ID, isDraftRecordId } from './draft'
11
- import {
12
- FieldTriggerEngine,
13
- getGlobalTriggerEngine,
14
- markOperationIrreversible,
15
- registerGlobalAction,
16
- registerTransitionAction,
17
- setFieldRollback,
18
- triggerTransition,
19
- } from './field-triggers'
20
- import plugin from './plugins'
21
- import Registry from './registry'
22
- import { Stonecrop } from './stonecrop'
23
- import { HST, createHST, type HSTNode } from './stores/hst'
24
- import { useOperationLogStore } from './stores/operation-log'
25
- import { useValidationStore } from './stores/validation'
26
- import { SchemaValidator, createValidator, validateSchema } from './schema-validator'
27
- import { ValidationSeverity } from './types/schema-validator'
28
-
29
- // Export all types from ./types
30
- export type * from './types'
31
-
32
- // clientHandler executor types
33
- export type { ClientHandlerApi } from './client-handler'
34
-
35
- // Field-validation store types
36
- export type { ValidationError } from './stores/validation'
37
-
38
- // Export enum as value (enums need runtime export, not just type)
39
- export { ValidationSeverity }
40
-
41
- export {
42
- Doctype,
43
- Registry,
44
- Stonecrop,
45
- // Unsaved-record identity, shared with the desktop shell
46
- DRAFT_RECORD_ID,
47
- isDraftRecordId,
48
- useLazyLink,
49
- useStonecrop,
50
- // clientHandler executor
51
- executeClientHandler,
52
- // The one blessed write path, shared by every Vue host
53
- useClientAction,
54
- // HST exports for advanced usage
55
- HST,
56
- createHST,
57
- HSTNode,
58
- // Field trigger system exports
59
- FieldTriggerEngine,
60
- getGlobalTriggerEngine,
61
- registerGlobalAction,
62
- registerTransitionAction,
63
- setFieldRollback,
64
- triggerTransition,
65
- markOperationIrreversible,
66
- // Schema validator exports
67
- SchemaValidator,
68
- createValidator,
69
- validateSchema,
70
- // Operation log exports
71
- useOperationLog,
72
- useOperationLogStore,
73
- useUndoRedoShortcuts,
74
- withBatch,
75
- // Field-validation store
76
- useValidationStore,
77
- // Utility functions
78
- }
79
-
80
- // Default export is the Vue plugin
81
- export default plugin
@@ -1,113 +0,0 @@
1
- import { App, type Plugin, nextTick } from 'vue'
2
- import type { Pinia } from 'pinia'
3
-
4
- import Registry from '../registry'
5
- import { Stonecrop } from '../stonecrop'
6
- import type { InstallOptions } from '../types'
7
- import { useOperationLogStore } from '../stores/operation-log'
8
-
9
- /**
10
- * Setup auto-initialization for user-defined initialization logic
11
- * This function handles the post-mount initialization automatically
12
- */
13
- async function setupAutoInitialization(
14
- registry: Registry,
15
- stonecrop: Stonecrop,
16
- onRouterInitialized: (registry: Registry, stonecrop: Stonecrop) => void | Promise<void>
17
- ) {
18
- // Wait for the next tick to ensure the app is mounted
19
- await nextTick()
20
-
21
- try {
22
- await onRouterInitialized(registry, stonecrop)
23
- } catch {
24
- // Silent error handling - application should handle initialization errors
25
- }
26
- }
27
-
28
- /**
29
- * Stonecrop Vue plugin
30
- * @param app - The Vue app instance
31
- * @param options - The plugin options
32
- * @example
33
- * ```ts
34
- * import { createApp } from 'vue'
35
- * import Stonecrop from '@stonecrop/stonecrop'
36
- * import { StonecropClient } from '@stonecrop/graphql-client'
37
- * import router from './router'
38
- *
39
- * const client = new StonecropClient({ endpoint: '/graphql' })
40
- *
41
- * const app = createApp(App)
42
- * app.use(Stonecrop, {
43
- * router,
44
- * client,
45
- * getMeta: async (routeContext) => {
46
- * // routeContext contains: { path, segments }
47
- * // use the client to fetch doctype meta
48
- * return client.getMeta({ doctype: routeContext.segments[0] })
49
- * },
50
- * autoInitializeRouter: true,
51
- * onRouterInitialized: async (registry, stonecrop) => {
52
- * // your custom initialization logic here
53
- * }
54
- * })
55
- * app.mount('#app')
56
- * ```
57
- * @public
58
- */
59
- const plugin: Plugin = {
60
- install: (app: App, options?: InstallOptions) => {
61
- // Check for existing router installation
62
- const existingRouter = app.config.globalProperties.$router
63
- const providedRouter = options?.router
64
- const router = existingRouter || providedRouter
65
- if (!existingRouter && providedRouter) {
66
- app.use(providedRouter)
67
- }
68
-
69
- // Create registry with available router
70
- const registry = new Registry(router, options?.getMeta)
71
- app.provide('$registry', registry)
72
- app.config.globalProperties.$registry = registry
73
-
74
- // Create and provide a global Stonecrop instance
75
- const stonecrop = new Stonecrop(registry)
76
- if (options?.client) {
77
- stonecrop.setClient(options.client)
78
- }
79
- app.provide('$stonecrop', stonecrop)
80
- app.config.globalProperties.$stonecrop = stonecrop
81
-
82
- // Initialize operation log store if Pinia is available
83
- // This ensures the store is created with the app's Pinia instance
84
- try {
85
- const pinia = app.config.globalProperties.$pinia as Pinia | undefined
86
- if (pinia) {
87
- // Initialize the operation log store with the app's Pinia instance
88
- const operationLogStore = useOperationLogStore(pinia)
89
-
90
- // Provide the store so components can access it
91
- app.provide('$operationLogStore', operationLogStore)
92
- app.config.globalProperties.$operationLogStore = operationLogStore
93
- }
94
- } catch (error) {
95
- // Pinia not available - operation log won't work, but app should still function
96
- console.warn('Pinia not available - operation log features will be disabled:', error)
97
- }
98
-
99
- // Register custom components
100
- if (options?.components) {
101
- for (const [tag, component] of Object.entries(options.components)) {
102
- app.component(tag, component)
103
- }
104
- }
105
-
106
- // Setup auto-initialization if requested
107
- if (options?.autoInitializeRouter && options.onRouterInitialized) {
108
- void setupAutoInitialization(registry, stonecrop, options.onRouterInitialized)
109
- }
110
- },
111
- }
112
-
113
- export default plugin
package/src/registry.ts DELETED
@@ -1,433 +0,0 @@
1
- import type { ResolvedField, ResolvedLink, ResolvedScalar, ResolvedTable, ResolvedFieldset } from '@stonecrop/aform'
2
- import { resolvedFieldsToColumns } from '@stonecrop/aform'
3
- import type { DoctypeField, LinkDeclaration, TableViewConfig, ValueField } from '@stonecrop/schema'
4
- import { componentCategory, componentLinkExpansion, resolveLinkRenderMode } from '@stonecrop/schema'
5
- import { Router } from 'vue-router'
6
-
7
- import Doctype from './doctype'
8
- import { RouteContext } from './types/registry'
9
-
10
- /**
11
- * Stonecrop Registry class
12
- * @public
13
- */
14
- export default class Registry {
15
- /**
16
- * The root Registry instance
17
- */
18
- static _root: Registry
19
-
20
- /**
21
- * The name of the Registry instance
22
- *
23
- * @defaultValue 'Registry'
24
- */
25
- readonly name: string = 'Registry'
26
-
27
- /**
28
- * The registry property contains a collection of doctypes
29
- *
30
- * @defaultValue `{}`
31
- * @see {@link Doctype}
32
- */
33
- readonly registry: Record<string, Doctype> = {}
34
-
35
- /**
36
- * Reverse index: backlink fieldname → list of \{ doctype slug, link fieldname \}.
37
- * Multiple doctypes can declare a link with the same backlink name, so each key
38
- * maps to an array. Built at schema load time for O(1) ancestor lookups.
39
- *
40
- * @defaultValue `new Map()`
41
- * @internal
42
- */
43
- private _ancestorIndex: Map<string, Array<{ slug: string; fieldname: string }>> = new Map()
44
-
45
- /**
46
- * Whether the ancestor index needs rebuilding
47
- *
48
- * @defaultValue `true`
49
- * @internal
50
- */
51
- private _ancestorIndexDirty: boolean = true
52
-
53
- /**
54
- * The Vue router instance
55
- * @see {@link https://router.vuejs.org/}
56
- */
57
- readonly router?: Router
58
-
59
- /**
60
- * Creates a new Registry instance (singleton pattern)
61
- * @param router - Optional Vue router instance for route management
62
- * @param getMeta - Optional function to fetch doctype metadata from an API
63
- */
64
- constructor(router?: Router, getMeta?: (routeContext: RouteContext) => Doctype | Promise<Doctype>) {
65
- if (Registry._root) {
66
- return Registry._root
67
- }
68
- Registry._root = this
69
- this.router = router
70
- this.getMeta = getMeta
71
- return this
72
- }
73
-
74
- /**
75
- * The getMeta function fetches doctype metadata from an API based on route context
76
- * @see {@link Doctype}
77
- */
78
- getMeta?: (routeContext: RouteContext) => Doctype | Promise<Doctype>
79
-
80
- /**
81
- * Get doctype metadata
82
- * @param doctype - The doctype to fetch metadata for
83
- * @returns The doctype metadata
84
- * @see {@link Doctype}
85
- */
86
- addDoctype(doctype: Doctype) {
87
- if (!(doctype.slug in this.registry)) {
88
- this.registry[doctype.slug] = doctype
89
- this._ancestorIndexDirty = true
90
- }
91
-
92
- // Field triggers are registered imperatively, by the app, via the FieldTriggerEngine's own
93
- // `registerDoctypeActions`. A doctype used to be able to declare them too, but that path
94
- // could not survive the wire — neither the Zod gate nor the SDL carries such a map — so it
95
- // only ever worked for a host bypassing both, and it left two public `runAction` methods
96
- // meaning opposite things. Registering here would also overwrite an app's imperative
97
- // registration, since `registerDoctypeActions` sets the maps even when handed nothing.
98
-
99
- if (doctype.component && this.router && !this.router.hasRoute(doctype.doctype)) {
100
- this.router.addRoute({
101
- path: `/${doctype.slug}`,
102
- name: doctype.slug,
103
- component: doctype.component,
104
- })
105
- }
106
- }
107
-
108
- /**
109
- * Resolve a Doctype's authoring schema into a rendered schema array suitable for AForm.
110
- *
111
- * Transforms `DoctypeField[]` (authoring space) → `ResolvedField[]` (rendering space):
112
- * - `kind: 'field'` (not Link) → `ResolvedScalar`
113
- * - `kind: 'field'` (Link, no declaration) → `ResolvedScalar` with `component: 'AFormLink'`
114
- * - `kind: 'field'` (Link, `noneOrMany`/`atLeastOne`) → `ResolvedTable`
115
- * - `kind: 'field'` (Link, `one`/`atMostOne`) → `ResolvedLink`
116
- * - `kind: 'fieldset'` → `ResolvedFieldset` (children resolved recursively)
117
- * - `kind: 'table'` → `ResolvedTable` (columns as `ColumnSchema[]`)
118
- *
119
- * Circular references are protected against via the `visited` set.
120
- *
121
- * @param doctype - The doctype to resolve
122
- * @param visited - Internal — set of already-visited doctype slugs for cycle detection
123
- * @returns A resolved schema array ready for AForm
124
- *
125
- * @public
126
- */
127
- resolveSchema(doctype: Doctype, visited?: Set<string>): ResolvedField[] {
128
- const seen = visited ?? new Set<string>()
129
- const slug = doctype.slug
130
-
131
- // Prevent circular resolution — return all ValueField entries as scalars (link not expanded)
132
- if (seen.has(slug)) {
133
- const fallback: DoctypeField[] = doctype.schema ? doctype.schema.toArray() : []
134
- return fallback
135
- .filter((f): f is ValueField => f.kind === 'field')
136
- .map(({ cardinality: _c, ...rest }): ResolvedScalar => rest)
137
- }
138
- seen.add(slug)
139
-
140
- const schemaArray: DoctypeField[] = doctype.schema ? doctype.schema.toArray() : []
141
-
142
- // Map link declarations by fieldname (link.fieldname ?? key)
143
- const linksByFieldname = new Map<string, LinkDeclaration>()
144
- if (doctype.links) {
145
- for (const [key, link] of Object.entries(doctype.links)) {
146
- linksByFieldname.set(link.fieldname ?? key, link)
147
- }
148
- }
149
-
150
- const result = this.resolveFields(schemaArray, linksByFieldname, seen)
151
- seen.delete(slug)
152
- return result
153
- }
154
-
155
- /**
156
- * Recursively resolve a `DoctypeField[]` using the provided link context.
157
- * Called by `resolveSchema` and recursively for fieldset children.
158
- * @internal
159
- */
160
- private resolveFields(
161
- fields: DoctypeField[],
162
- links: Map<string, LinkDeclaration>,
163
- visited: Set<string>
164
- ): ResolvedField[] {
165
- const resolved: ResolvedField[] = []
166
-
167
- for (const field of fields) {
168
- // A field is a link when it carries `doctype` (the marker) or has a LinkDeclaration.
169
- const linkDecl = field.kind === 'field' ? links.get(field.fieldname) : undefined
170
- if (field.kind === 'field' && (linkDecl || field.doctype)) {
171
- const link = linkDecl
172
- // The declaration's target wins over the field's own `doctype`.
173
- const linkTarget = link?.target ?? field.doctype
174
-
175
- // An undeclared link, or a declared one whose component renders an inline picker,
176
- // stays a scalar: the target is not expanded, it only needs the slug for async
177
- // display-text resolution and navigation.
178
- if (!link || resolveLinkRenderMode(link, field.component) === 'inline') {
179
- const { cardinality: _c, ...rest } = field
180
- resolved.push({
181
- ...rest,
182
- component: rest.component || 'AFormLink',
183
- ...(linkTarget !== undefined ? { doctype: linkTarget } : {}),
184
- })
185
- continue
186
- }
187
-
188
- const targetDoctype = this.registry[link.target]
189
- if (!targetDoctype) {
190
- // Target not registered — copy as scalar
191
- const { cardinality: _c, ...rest } = field
192
- resolved.push({ ...rest })
193
- continue
194
- }
195
-
196
- const childSchema = this.resolveSchema(targetDoctype, new Set(visited))
197
- const { options: _opt, cardinality: _card, kind: _kind, ...fieldRest } = field
198
-
199
- if (resolveLinkRenderMode(link, field.component) === 'table') {
200
- resolved.push(this.buildTableConfig(field, childSchema, link.component))
201
- } else {
202
- const linkEntry: ResolvedLink = {
203
- ...fieldRest,
204
- kind: 'link',
205
- label: fieldRest.label || field.fieldname,
206
- component: link.component || fieldRest.component || 'AForm',
207
- schema: childSchema,
208
- }
209
- resolved.push(linkEntry)
210
- }
211
- } else if (field.kind === 'fieldset') {
212
- const resolvedChildren = this.resolveFields(field.schema, links, visited)
213
- const { schema: _s, ...fieldRest } = field
214
- const fieldsetEntry: ResolvedFieldset = {
215
- ...fieldRest,
216
- schema: resolvedChildren,
217
- }
218
- resolved.push(fieldsetEntry)
219
- } else if (field.kind === 'table') {
220
- // Inline table — columns become ColumnSchema[], add default config
221
- const { columns, config, ...fieldRest } = field
222
- const tableEntry: ResolvedTable = {
223
- ...fieldRest,
224
- kind: 'table',
225
- component: fieldRest.component || 'ATable',
226
- schema: columns,
227
- config: config ?? { view: 'list' },
228
- }
229
- resolved.push(tableEntry)
230
- } else {
231
- // Scalar field (kind: 'field', not a link) — strip cardinality.
232
- // A link-rendering component with nothing to point at renders an empty picker (or an
233
- // empty embedded form), which is indistinguishable from "the record has no value".
234
- // Link-ness comes from `doctype`/`links`, so this is a field that named a link
235
- // component and forgot the target.
236
- if (field.kind === 'field' && componentLinkExpansion(field.component)) {
237
- console.warn(
238
- `[Stonecrop] Field "${field.fieldname}" renders with "${field.component}", which is a link component, ` +
239
- `but the field is not a link: it has no \`doctype\` and no \`links\` declaration. It will render ` +
240
- `as a plain field. Add \`"doctype": "<doctype-slug>"\` to the field definition.`
241
- )
242
- }
243
- const { cardinality: _c, ...rest } = field
244
- resolved.push({ ...rest })
245
- }
246
- }
247
-
248
- return resolved
249
- }
250
-
251
- /**
252
- * Build a `ResolvedTable` from a resolved Link field with many cardinality.
253
- * Columns come from {@link @stonecrop/aform#resolvedFieldsToColumns}, the shared definition of
254
- * which resolved fields a cell can render.
255
- * @internal
256
- */
257
- private buildTableConfig(field: ValueField, childSchema: ResolvedField[], component?: string): ResolvedTable {
258
- const columns = resolvedFieldsToColumns(childSchema)
259
-
260
- const config: TableViewConfig = (field as ValueField & { config?: TableViewConfig }).config ?? { view: 'list' }
261
- const { options: _opt, cardinality: _card, ...fieldRest } = field
262
-
263
- return {
264
- ...fieldRest,
265
- kind: 'table',
266
- label: fieldRest.label || field.fieldname,
267
- component: component || fieldRest.component || 'ATable',
268
- schema: columns,
269
- config,
270
- }
271
- }
272
-
273
- /**
274
- * Initialize a new record with default values based on a resolved schema.
275
- * Narrows by `kind` discriminator for precise branch selection.
276
- *
277
- * - `kind: 'table'` or `kind: 'link'` → `[]` or `{}`
278
- * - `kind: 'fieldset'` → recursively initializes children as `{}`
279
- * - `kind: 'field'` → derives the default from the component's category; falls back to `null`
280
- *
281
- * @param schema - The resolved schema array to derive defaults from
282
- * @returns A plain object with default values for each field
283
- * @public
284
- */
285
- initializeRecord(schema: ResolvedField[]): Record<string, any> {
286
- const record: Record<string, any> = {}
287
-
288
- for (const field of schema) {
289
- if (field.kind === 'table') {
290
- record[field.fieldname] = []
291
- } else if (field.kind === 'link') {
292
- record[field.fieldname] = this.initializeRecord(field.schema)
293
- } else if (field.kind === 'fieldset') {
294
- record[field.fieldname] = this.initializeRecord(field.schema)
295
- } else {
296
- // kind: 'field' — the empty default comes from the component's category.
297
- const fieldDefault = field.default
298
- if (fieldDefault !== undefined) {
299
- record[field.fieldname] = fieldDefault
300
- } else {
301
- const category = componentCategory(field.component)
302
- if (category === 'text') {
303
- record[field.fieldname] = ''
304
- } else if (category === 'number') {
305
- record[field.fieldname] = 0
306
- } else if (category === 'boolean') {
307
- record[field.fieldname] = false
308
- } else if (category === 'code' && field.language) {
309
- // A JSON editor starts from an empty object; any other language from empty source.
310
- record[field.fieldname] = field.language === 'json' ? {} : ''
311
- } else {
312
- // date / datetime / select / link / attach — plus two cases with no better answer
313
- // than "no value": an unknown (custom) component, and a code field whose missing
314
- // `language` doesn't say which kind of empty it wants.
315
- record[field.fieldname] = null
316
- }
317
- }
318
- }
319
- }
320
-
321
- return record
322
- }
323
-
324
- /**
325
- * Get a registered doctype by slug
326
- * @param slug - The doctype slug to look up
327
- * @returns The Doctype instance if found, or undefined
328
- * @public
329
- */
330
- getDoctype(slug: string): Doctype | undefined {
331
- return this.registry[slug]
332
- }
333
-
334
- /**
335
- * Get all links declared on a doctype.
336
- *
337
- * @param doctypeSlug - The doctype slug to get links for
338
- * @returns Array of link declarations with fieldname, or empty array if none
339
- *
340
- * @example
341
- * ```ts
342
- * const links = registry.getDescendantLinks('recipe')
343
- * // [{ fieldname: 'tasks', target: 'recipe-task', cardinality: 'noneOrMany', backlink: 'recipe' }]
344
- * ```
345
- *
346
- * @public
347
- */
348
- getDescendantLinks(doctypeSlug: string): Array<LinkDeclaration & { fieldname: string }> {
349
- const doctype = this.registry[doctypeSlug]
350
- if (!doctype?.links) return []
351
-
352
- return Object.entries(doctype.links).map(([fieldname, link]) =>
353
- Object.assign({}, link, {
354
- fieldname,
355
- })
356
- )
357
- }
358
-
359
- /**
360
- * Get links on other doctypes that target the given doctype.
361
- *
362
- * @param doctypeSlug - The doctype slug to find ancestor links for
363
- * @returns Array of link declarations with fieldname and declaring doctype slug, or empty array
364
- *
365
- * @example
366
- * ```ts
367
- * const ancestors = registry.getAncestorLinks('recipe-task')
368
- * // [{ fieldname: 'tasks', target: 'recipe-task', cardinality: 'noneOrMany', backlink: 'recipe', doctype: 'recipe' }]
369
- * ```
370
- *
371
- * @public
372
- */
373
- getAncestorLinks(doctypeSlug: string): Array<LinkDeclaration & { fieldname: string; doctype: string }> {
374
- this._ensureAncestorIndex()
375
-
376
- const results: Array<LinkDeclaration & { fieldname: string; doctype: string }> = []
377
-
378
- for (const [_backlink, entries] of this._ancestorIndex) {
379
- for (const { slug: declaringSlug, fieldname } of entries) {
380
- const declaringDoctype = this.registry[declaringSlug]
381
- if (!declaringDoctype?.links) continue
382
-
383
- const link = declaringDoctype.links[fieldname]
384
- if (link?.target === doctypeSlug) {
385
- results.push({
386
- ...link,
387
- fieldname,
388
- doctype: declaringSlug,
389
- })
390
- }
391
- }
392
- }
393
-
394
- return results
395
- }
396
-
397
- /**
398
- * Ensure the ancestor index is up to date
399
- * @internal
400
- */
401
- private _ensureAncestorIndex(): void {
402
- if (!this._ancestorIndexDirty) return
403
- this._ancestorIndexDirty = false
404
- this._ancestorIndex.clear()
405
-
406
- for (const [slug, doctype] of Object.entries(this.registry)) {
407
- if (!doctype.links) continue
408
- for (const [fieldname, link] of Object.entries(doctype.links)) {
409
- if (link.backlink) {
410
- const existing = this._ancestorIndex.get(link.backlink)
411
- if (existing) {
412
- existing.push({ slug, fieldname })
413
- } else {
414
- this._ancestorIndex.set(link.backlink, [{ slug, fieldname }])
415
- }
416
- }
417
- }
418
- }
419
- }
420
-
421
- // TODO: should we allow clearing the registry at all?
422
- // clear() {
423
- // this.registry = {}
424
- // if (this.router) {
425
- // const routes = this.router.getRoutes()
426
- // for (const route of routes) {
427
- // if (route.name) {
428
- // this.router.removeRoute(route.name)
429
- // }
430
- // }
431
- // }
432
- // }
433
- }