@stonecrop/stonecrop 0.13.14 → 0.15.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 (95) hide show
  1. package/README.md +6 -3
  2. package/dist/src/doctype.d.ts +42 -7
  3. package/dist/src/doctype.d.ts.map +1 -1
  4. package/dist/src/doctype.js +77 -18
  5. package/dist/src/index.d.ts +5 -1
  6. package/dist/src/index.d.ts.map +1 -1
  7. package/dist/src/index.js +6 -0
  8. package/dist/src/registry.d.ts +1 -1
  9. package/dist/src/registry.d.ts.map +1 -1
  10. package/dist/src/registry.js +46 -38
  11. package/dist/src/schema-validator.d.ts.map +1 -1
  12. package/dist/src/schema-validator.js +44 -47
  13. package/dist/src/stonecrop.d.ts +0 -6
  14. package/dist/src/stonecrop.d.ts.map +1 -1
  15. package/dist/src/stores/index.d.ts +2 -0
  16. package/dist/src/stores/index.d.ts.map +1 -1
  17. package/dist/src/stores/index.js +1 -0
  18. package/dist/src/stores/operation-log.d.ts +0 -6
  19. package/dist/src/stores/operation-log.d.ts.map +1 -1
  20. package/dist/src/stores/operation-log.js +0 -1
  21. package/dist/src/stores/validation.d.ts +83 -0
  22. package/dist/src/stores/validation.d.ts.map +1 -0
  23. package/dist/src/stores/validation.js +104 -0
  24. package/dist/src/types/doctype.d.ts +1 -1
  25. package/dist/src/types/doctype.d.ts.map +1 -1
  26. package/dist/src/types/operation-log.d.ts +0 -2
  27. package/dist/src/types/operation-log.d.ts.map +1 -1
  28. package/dist/stonecrop.d.ts +166 -22
  29. package/dist/stonecrop.js +5235 -1950
  30. package/dist/stonecrop.js.map +1 -1
  31. package/package.json +23 -23
  32. package/src/client-handler.ts +55 -0
  33. package/src/doctype.ts +83 -22
  34. package/src/index.ts +12 -0
  35. package/src/registry.ts +45 -40
  36. package/src/schema-validator.ts +52 -48
  37. package/src/stores/index.ts +2 -0
  38. package/src/stores/operation-log.ts +0 -1
  39. package/src/stores/validation.ts +138 -0
  40. package/src/types/doctype.ts +1 -1
  41. package/src/types/operation-log.ts +0 -3
  42. package/dist/composable.js +0 -1
  43. package/dist/composables/lazy-link.js +0 -125
  44. package/dist/composables/operation-log.js +0 -224
  45. package/dist/composables/stonecrop.js +0 -504
  46. package/dist/composables/use-lazy-link-state.js +0 -125
  47. package/dist/composables/use-stonecrop.js +0 -476
  48. package/dist/doctype.js +0 -242
  49. package/dist/exceptions.js +0 -16
  50. package/dist/field-triggers.js +0 -575
  51. package/dist/index.js +0 -27
  52. package/dist/operation-log-DB-dGNT9.js +0 -593
  53. package/dist/operation-log-DB-dGNT9.js.map +0 -1
  54. package/dist/plugins/index.js +0 -99
  55. package/dist/registry.js +0 -423
  56. package/dist/schema-validator.js +0 -407
  57. package/dist/src/composable.d.ts +0 -11
  58. package/dist/src/composable.d.ts.map +0 -1
  59. package/dist/src/composable.js +0 -477
  60. package/dist/src/composables/use-lazy-link-state.d.ts +0 -25
  61. package/dist/src/composables/use-lazy-link-state.d.ts.map +0 -1
  62. package/dist/src/composables/use-stonecrop.d.ts +0 -93
  63. package/dist/src/composables/use-stonecrop.d.ts.map +0 -1
  64. package/dist/src/composables/useNestedSchema.d.ts +0 -110
  65. package/dist/src/composables/useNestedSchema.d.ts.map +0 -1
  66. package/dist/src/composables/useNestedSchema.js +0 -155
  67. package/dist/src/stores/data.d.ts +0 -11
  68. package/dist/src/stores/data.d.ts.map +0 -1
  69. package/dist/src/stores/xstate.d.ts +0 -31
  70. package/dist/src/stores/xstate.d.ts.map +0 -1
  71. package/dist/src/tsdoc-metadata.json +0 -11
  72. package/dist/src/utils.d.ts +0 -24
  73. package/dist/src/utils.d.ts.map +0 -1
  74. package/dist/stonecrop.css +0 -1
  75. package/dist/stonecrop.umd.cjs +0 -6
  76. package/dist/stonecrop.umd.cjs.map +0 -1
  77. package/dist/stores/data.js +0 -7
  78. package/dist/stores/hst.js +0 -496
  79. package/dist/stores/index.js +0 -12
  80. package/dist/stores/operation-log.js +0 -580
  81. package/dist/stores/xstate.js +0 -29
  82. package/dist/tests/setup.d.ts +0 -5
  83. package/dist/tests/setup.d.ts.map +0 -1
  84. package/dist/tests/setup.js +0 -15
  85. package/dist/types/composable.js +0 -0
  86. package/dist/types/doctype.js +0 -0
  87. package/dist/types/field-triggers.js +0 -4
  88. package/dist/types/hst.js +0 -0
  89. package/dist/types/index.js +0 -10
  90. package/dist/types/operation-log.js +0 -0
  91. package/dist/types/plugin.js +0 -0
  92. package/dist/types/registry.js +0 -0
  93. package/dist/types/schema-validator.js +0 -13
  94. package/dist/types/stonecrop.js +0 -0
  95. package/dist/utils.js +0 -46
@@ -16,4 +16,6 @@ pinia.use(
16
16
 
17
17
  export { hst, pinia }
18
18
  export { useOperationLogStore } from './operation-log'
19
+ export { useValidationStore } from './validation'
20
+ export type { ValidationError } from './validation'
19
21
  export type { HSTNode } from './hst'
@@ -116,7 +116,6 @@ export const useOperationLogStore = defineStore('hst-operation-log', () => {
116
116
  const config = ref<OperationLogConfig>({
117
117
  maxOperations: 100,
118
118
  enableCrossTabSync: true,
119
- autoSyncInterval: 30000,
120
119
  enablePersistence: false,
121
120
  persistenceKeyPrefix: 'stonecrop-ops',
122
121
  })
@@ -0,0 +1,138 @@
1
+ import { defineStore } from 'pinia'
2
+ import { ref, computed } from 'vue'
3
+
4
+ import type { TriggerDefinition } from '@stonecrop/schema'
5
+ import { executeClientHandler } from '../client-handler'
6
+
7
+ /**
8
+ * A single validation error contributed by a trigger, displayed on a field.
9
+ * @public
10
+ */
11
+ export interface ValidationError {
12
+ /** The trigger that produced this error — the namespace a re-run clears before repopulating */
13
+ trigger: string
14
+ /** The fieldname the error displays on (the `setError` target, not necessarily a fired field) */
15
+ field: string
16
+ /** The message to display */
17
+ message: string
18
+ }
19
+
20
+ /**
21
+ * Reactive per-field validation error store + the advisory field-validation trigger engine.
22
+ *
23
+ * Holds the errors produced by field-validation triggers (see `TriggerDefinition` in
24
+ * `@stonecrop/schema`) and runs a trigger's `clientHandler` on demand. Errors are **namespaced
25
+ * by trigger**: re-running a trigger clears its own prior contributions before repopulating, so a
26
+ * corrected value clears its stale error without disturbing other triggers.
27
+ *
28
+ * The engine is **advisory** and does **no rollback** — an invalid value stays in the record so the
29
+ * user can fix it; validity is reported separately via `isValid` (read by the save gate) and
30
+ * the per-field messages are surfaced via `errorsByField` / `errorsFor` for display.
31
+ *
32
+ * @public
33
+ */
34
+ export const useValidationStore = defineStore('stonecrop-validation', () => {
35
+ const errors = ref<ValidationError[]>([])
36
+
37
+ /** True when no field currently carries a validation error. */
38
+ const isValid = computed(() => errors.value.length === 0)
39
+
40
+ /** Errors grouped by field — the shape a renderer consumes (e.g. AForm `:errors`). */
41
+ const errorsByField = computed<Record<string, string[]>>(() => {
42
+ const map: Record<string, string[]> = {}
43
+ for (const e of errors.value) {
44
+ if (!map[e.field]) map[e.field] = []
45
+ map[e.field].push(e.message)
46
+ }
47
+ return map
48
+ })
49
+
50
+ /** Messages currently displayed on `field`. */
51
+ function errorsFor(field: string): string[] {
52
+ return errors.value.filter(e => e.field === field).map(e => e.message)
53
+ }
54
+
55
+ /** Record an error contributed by `trigger`, displayed on `field`. */
56
+ function setError(trigger: string, field: string, message: string) {
57
+ errors.value.push({ trigger, field, message })
58
+ }
59
+
60
+ /** Remove every error contributed by `trigger` (its namespace). */
61
+ function clearTrigger(trigger: string) {
62
+ errors.value = errors.value.filter(e => e.trigger !== trigger)
63
+ }
64
+
65
+ /** Remove every validation error. */
66
+ function clearAll() {
67
+ errors.value = []
68
+ }
69
+
70
+ /**
71
+ * Run a single trigger against a read-only snapshot of `record`. Clears the trigger's prior
72
+ * errors, then executes its `clientHandler` with `{ record, value, setError }`. Fails **open** —
73
+ * a throwing validator warns and records nothing, so a broken validator never blocks the user.
74
+ */
75
+ async function runTrigger(name: string, def: TriggerDefinition, record: Record<string, unknown>, value: unknown) {
76
+ clearTrigger(name)
77
+ // Shallow-frozen copy: the validator reads siblings but can neither mutate the record nor
78
+ // reassign fields (advisory reads only) — and mutation can't leak back to the caller.
79
+ const frozen = Object.freeze({ ...record })
80
+ const boundSetError = (field: string, message: string) => setError(name, field, message)
81
+ try {
82
+ await executeClientHandler(def.clientHandler, { record: frozen, value, setError: boundSetError })
83
+ } catch (error) {
84
+ // Advisory by design: a broken validator must never block save (a bug in one trigger must
85
+ // not trap the user, especially in production). It fails OPEN — but a throw is an error in
86
+ // the author's code, so surface it loudly (error severity, trigger named) rather than
87
+ // silently: a broken validator that just "does nothing" is the real footgun here.
88
+ if (typeof console !== 'undefined') {
89
+ console.error(
90
+ `Validation trigger "${name}" threw and was ignored (advisory — save is not blocked). ` +
91
+ `Fix its clientHandler:`,
92
+ error
93
+ )
94
+ }
95
+ }
96
+ }
97
+
98
+ /**
99
+ * Run every trigger whose `on` set includes `changedField`, passing that field's current value.
100
+ * Call on the edit path (desktop-driven) so editing either bound field re-validates the pair.
101
+ */
102
+ async function validateField(
103
+ triggers: Record<string, TriggerDefinition>,
104
+ changedField: string,
105
+ record: Record<string, unknown>
106
+ ): Promise<void> {
107
+ const runs: Promise<void>[] = []
108
+ for (const [name, def] of Object.entries(triggers)) {
109
+ if (def.on.includes(changedField)) {
110
+ runs.push(runTrigger(name, def, record, record[changedField]))
111
+ }
112
+ }
113
+ await Promise.all(runs)
114
+ }
115
+
116
+ /**
117
+ * Run **all** triggers (no fired-field filter) — the authoritative client gate at save-attempt,
118
+ * covering triggers whose fields were never edited. `value` is undefined (no single changed field).
119
+ */
120
+ async function validateRecord(
121
+ triggers: Record<string, TriggerDefinition>,
122
+ record: Record<string, unknown>
123
+ ): Promise<void> {
124
+ await Promise.all(Object.entries(triggers).map(([name, def]) => runTrigger(name, def, record, undefined)))
125
+ }
126
+
127
+ return {
128
+ errors,
129
+ isValid,
130
+ errorsByField,
131
+ errorsFor,
132
+ setError,
133
+ clearTrigger,
134
+ clearAll,
135
+ validateField,
136
+ validateRecord,
137
+ }
138
+ })
@@ -23,7 +23,7 @@ export type DoctypeConfig = {
23
23
  name: string
24
24
  /** URL-friendly slug (kebab-case) */
25
25
  slug?: string
26
- /** Field definitions (including link fields with fieldtype: 'Link') */
26
+ /** Field definitions (a link field is one carrying `doctype`) */
27
27
  fields?: DoctypeField[]
28
28
  /** Relationship links to other doctypes */
29
29
  links?: Record<string, LinkDeclaration>
@@ -123,9 +123,6 @@ export interface OperationLogConfig {
123
123
  /** Enable cross-tab synchronization (default: true) */
124
124
  enableCrossTabSync?: boolean
125
125
 
126
- /** Auto-sync interval in milliseconds (default: 30000) */
127
- autoSyncInterval?: number
128
-
129
126
  /** Enable operation persistence to localStorage (default: false) */
130
127
  enablePersistence?: boolean
131
128
 
@@ -1 +0,0 @@
1
- export { useStonecrop } from './composables/stonecrop';
@@ -1,125 +0,0 @@
1
- import { computed, inject, ref } from 'vue';
2
- import { Stonecrop } from '../stonecrop';
3
- /**
4
- * Get the lazy link state for a specific link field on a doctype record.
5
- *
6
- * This composable provides reactive state for lazy-loaded links:
7
- * - `loading`: true while fetching
8
- * - `loaded`: true after successful fetch (permanent until reload)
9
- * - `error`: error state if any
10
- * - `reload()`: explicitly trigger a fetch
11
- * - `data`: computed from HST, or undefined if not loaded
12
- *
13
- * The reload() function respects the link's fetch strategy:
14
- * - `sync`: fetches via GraphQL query through fetchNestedData
15
- * - `lazy`: fetches via GraphQL query through fetchNestedData
16
- * - `custom`: invokes the serialized handler function directly
17
- *
18
- * @param doctype - The doctype instance
19
- * @param recordId - The record ID
20
- * @param linkFieldname - The link fieldname to load
21
- * @returns LazyLink with loading, loaded, error, reload, and data
22
- * @public
23
- */
24
- export function useLazyLink(doctype, recordId, linkFieldname) {
25
- const stonecropInstance = inject('$stonecrop') || Stonecrop._root;
26
- if (!stonecropInstance) {
27
- throw new Error('Stonecrop instance not available. Ensure useStonecrop() has been called first.');
28
- }
29
- const loading = ref(false);
30
- const loaded = ref(false);
31
- const error = ref(null);
32
- const hstStore = stonecropInstance.getStore();
33
- /**
34
- * Build the HST path for a lazy link field
35
- */
36
- const getLinkPath = () => {
37
- const slug = doctype.slug || doctype.doctype;
38
- return `${slug}.${recordId}.${linkFieldname}`;
39
- };
40
- /**
41
- * Get the link declaration from the doctype schema
42
- */
43
- const getLinkDeclaration = () => {
44
- return doctype.links?.[linkFieldname]?.fetch;
45
- };
46
- /**
47
- * Invoke a custom fetch handler
48
- * The handler is a serialized function string that we execute via new Function()
49
- */
50
- const invokeCustomHandler = async (handler) => {
51
- try {
52
- // Create function from serialized string and invoke it
53
- // The function receives the stonecrop instance and path as parameters
54
- // eslint-disable-next-line @typescript-eslint/no-implied-eval
55
- const fn = new Function('stonecrop', 'path', 'hst', `
56
- return (${handler})(stonecrop, path, hst)
57
- `);
58
- // eslint-disable-next-line @typescript-eslint/no-unsafe-call
59
- return await fn(stonecropInstance, getLinkPath(), hstStore);
60
- }
61
- catch (err) {
62
- throw new Error(`Custom handler failed: ${err instanceof Error ? err.message : String(err)}`);
63
- }
64
- };
65
- /**
66
- * Fetch the link data using the appropriate strategy
67
- */
68
- const fetchLinkData = async () => {
69
- const linkFetch = getLinkDeclaration();
70
- const ancestorPath = `${doctype.slug || doctype.doctype}.${recordId}`;
71
- if (linkFetch?.method === 'custom') {
72
- // Ensure ancestor path exists before invoking custom handler
73
- if (!hstStore.has(ancestorPath)) {
74
- hstStore.set(ancestorPath, {}, 'system');
75
- }
76
- // Custom handler - invoke directly
77
- const result = await invokeCustomHandler(linkFetch.handler);
78
- // Store result in HST at the link path
79
- hstStore.set(getLinkPath(), result, 'system');
80
- }
81
- else {
82
- // sync or lazy (both use fetchNestedData but with different includeNested)
83
- // For lazy links, we still use fetchNestedData but only for this specific link
84
- await stonecropInstance.fetchNestedData(ancestorPath, doctype, recordId, { includeNested: [linkFieldname] });
85
- }
86
- };
87
- /**
88
- * Explicitly reload the lazy link data
89
- */
90
- const reload = async () => {
91
- if (loading.value)
92
- return;
93
- loading.value = true;
94
- error.value = null;
95
- try {
96
- await fetchLinkData();
97
- loaded.value = true;
98
- }
99
- catch (err) {
100
- error.value = err instanceof Error ? err : new Error(String(err));
101
- throw err;
102
- }
103
- finally {
104
- loading.value = false;
105
- }
106
- };
107
- /**
108
- * Computed property that returns the loaded data from HST
109
- */
110
- const data = computed(() => {
111
- if (!loaded.value)
112
- return undefined;
113
- return hstStore.get(getLinkPath());
114
- });
115
- return {
116
- // State
117
- loading,
118
- loaded,
119
- error,
120
- // Computed
121
- data,
122
- // Actions
123
- reload,
124
- };
125
- }
@@ -1,224 +0,0 @@
1
- import { useMagicKeys, whenever } from '@vueuse/core';
2
- import { storeToRefs } from 'pinia';
3
- import { getCurrentInstance, inject } from 'vue';
4
- import { useOperationLogStore } from '../stores/operation-log';
5
- /**
6
- * Composable for operation log management
7
- * Provides easy access to undo/redo functionality and operation history
8
- *
9
- * @param config - Optional configuration for the operation log
10
- * @returns Operation log interface
11
- *
12
- * @example
13
- * ```typescript
14
- * const { undo, redo, canUndo, canRedo, operations, configure } = useOperationLog()
15
- *
16
- * // Configure the log
17
- * configure({
18
- * maxOperations: 50,
19
- * enableCrossTabSync: true,
20
- * enablePersistence: true
21
- * })
22
- *
23
- * // Undo/redo
24
- * await undo(hstStore)
25
- * await redo(hstStore)
26
- * ```
27
- *
28
- * @public
29
- */
30
- export function useOperationLog(config) {
31
- // inject() is only valid inside a component setup() context. When this
32
- // composable is called outside one (e.g. directly in test bodies or plain
33
- // scripts) skip the injection entirely and fall back to the Pinia store.
34
- const injectedStore = getCurrentInstance()
35
- ? inject('$operationLogStore', undefined)
36
- : undefined;
37
- const store = injectedStore || useOperationLogStore();
38
- // Apply configuration if provided
39
- if (config) {
40
- store.configure(config);
41
- }
42
- // Extract reactive state
43
- const { operations, currentIndex, undoRedoState, canUndo, canRedo, undoCount, redoCount } = storeToRefs(store);
44
- /**
45
- * Undo the last operation
46
- */
47
- function undo(hstStore) {
48
- return store.undo(hstStore);
49
- }
50
- /**
51
- * Redo the next operation
52
- */
53
- function redo(hstStore) {
54
- return store.redo(hstStore);
55
- }
56
- /**
57
- * Start a batch operation
58
- */
59
- function startBatch() {
60
- store.startBatch();
61
- }
62
- /**
63
- * Commit the current batch
64
- */
65
- function commitBatch(description) {
66
- return store.commitBatch(description);
67
- }
68
- /**
69
- * Cancel the current batch
70
- */
71
- function cancelBatch() {
72
- store.cancelBatch();
73
- }
74
- /**
75
- * Clear all operations
76
- */
77
- function clear() {
78
- store.clear();
79
- }
80
- /**
81
- * Get operations for a specific doctype/record
82
- */
83
- function getOperationsFor(doctype, recordId) {
84
- return store.getOperationsFor(doctype, recordId);
85
- }
86
- /**
87
- * Get a snapshot of the operation log
88
- */
89
- function getSnapshot() {
90
- return store.getSnapshot();
91
- }
92
- /**
93
- * Mark an operation as irreversible
94
- * @param operationId - The ID of the operation to mark
95
- * @param reason - The reason why the operation is irreversible
96
- */
97
- function markIrreversible(operationId, reason) {
98
- store.markIrreversible(operationId, reason);
99
- }
100
- /**
101
- * Log an action execution (stateless actions like print, email, etc.)
102
- * @param doctype - The doctype the action was executed on
103
- * @param actionName - The name of the action that was executed
104
- * @param recordIds - Optional array of record IDs the action was executed on
105
- * @param result - The result of the action execution
106
- * @param error - Optional error message if action failed
107
- * @returns The operation ID
108
- */
109
- function logAction(doctype, actionName, recordIds, result = 'success', error) {
110
- return store.logAction(doctype, actionName, recordIds, result, error);
111
- }
112
- /**
113
- * Update configuration
114
- * @param options - Configuration options to update
115
- */
116
- function configure(options) {
117
- store.configure(options);
118
- }
119
- return {
120
- // State
121
- operations,
122
- currentIndex,
123
- undoRedoState,
124
- canUndo,
125
- canRedo,
126
- undoCount,
127
- redoCount,
128
- // Methods
129
- undo,
130
- redo,
131
- startBatch,
132
- commitBatch,
133
- cancelBatch,
134
- clear,
135
- getOperationsFor,
136
- getSnapshot,
137
- markIrreversible,
138
- logAction,
139
- configure,
140
- };
141
- }
142
- /**
143
- * Keyboard shortcut handler for undo/redo
144
- * Automatically binds Ctrl+Z (undo) and Ctrl+Shift+Z/Ctrl+Y (redo) using VueUse
145
- *
146
- * @param hstStore - The HST store to operate on
147
- * @param enabled - Whether shortcuts are enabled (default: true)
148
- *
149
- * @example
150
- * ```typescript
151
- * import { onMounted } from 'vue'
152
- *
153
- * const stonecrop = useStonecrop({ doctype, recordId })
154
- * useUndoRedoShortcuts(stonecrop.hstStore)
155
- * ```
156
- *
157
- * @public
158
- */
159
- export function useUndoRedoShortcuts(hstStore, enabled = true) {
160
- if (!enabled)
161
- return;
162
- const { undo, redo, canUndo, canRedo } = useOperationLog();
163
- const keys = useMagicKeys();
164
- // Undo shortcuts: Ctrl+Z or Cmd+Z (Mac)
165
- whenever(keys['Ctrl+Z'], () => {
166
- if (canUndo.value) {
167
- undo(hstStore);
168
- }
169
- });
170
- whenever(keys['Meta+Z'], () => {
171
- if (canUndo.value) {
172
- undo(hstStore);
173
- }
174
- });
175
- // Redo shortcuts: Ctrl+Shift+Z, Cmd+Shift+Z (Mac), or Ctrl+Y
176
- whenever(keys['Ctrl+Shift+Z'], () => {
177
- if (canRedo.value) {
178
- redo(hstStore);
179
- }
180
- });
181
- whenever(keys['Meta+Shift+Z'], () => {
182
- if (canRedo.value) {
183
- redo(hstStore);
184
- }
185
- });
186
- whenever(keys['Ctrl+Y'], () => {
187
- if (canRedo.value) {
188
- redo(hstStore);
189
- }
190
- });
191
- }
192
- /**
193
- * Batch operation helper
194
- * Wraps a function execution in a batch operation
195
- *
196
- * @param fn - The function to execute within a batch
197
- * @param description - Optional description for the batch
198
- * @returns The batch operation ID
199
- *
200
- * @example
201
- * ```typescript
202
- * const { withBatch } = useOperationLog()
203
- *
204
- * const batchId = await withBatch(() => {
205
- * hstStore.set('task.123.title', 'New Title')
206
- * hstStore.set('task.123.status', 'active')
207
- * hstStore.set('task.123.priority', 'high')
208
- * }, 'Update task details')
209
- * ```
210
- *
211
- * @public
212
- */
213
- export async function withBatch(fn, description) {
214
- const { startBatch, commitBatch, cancelBatch } = useOperationLog();
215
- startBatch();
216
- try {
217
- await fn();
218
- return commitBatch(description);
219
- }
220
- catch (error) {
221
- cancelBatch();
222
- throw error;
223
- }
224
- }