@stonecrop/stonecrop 0.49.0 → 0.50.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.
@@ -565,6 +565,19 @@ export declare type DoctypeDefaults = {
565
565
  */
566
566
  export declare const DRAFT_RECORD_ID = "new";
567
567
 
568
+ /**
569
+ * The record a form is editing, read and set by field name. Setting a field runs that field's
570
+ * rules, whether the record is saved or not saved yet.
571
+ *
572
+ * @public
573
+ */
574
+ export declare interface EditableRecord {
575
+ /** Reads a field, or the whole record when `fieldname` is `''` */
576
+ get(fieldname: string): any;
577
+ /** Sets a field, which runs that field's rules */
578
+ set(fieldname: string, value: any): void;
579
+ }
580
+
568
581
  /**
569
582
  * Execute a docbuilder-authored `clientHandler` body against an injected API map.
570
583
  *
@@ -614,12 +627,13 @@ export declare type FieldActionFunction = (context: FieldChangeContext) => void
614
627
  export declare type FieldActionString = string;
615
628
 
616
629
  /**
617
- * Context provided to action functions when field changes occur
630
+ * Context provided to action functions when field changes occur. Its `get` and `set` reach the
631
+ * record whose field changed, saved or not saved yet.
618
632
  * @public
619
633
  */
620
- export declare interface FieldChangeContext {
621
- /** The HST path that was changed */
622
- path: string;
634
+ export declare interface FieldChangeContext extends EditableRecord {
635
+ /** The HST path that was changed; absent for a record not saved yet, which is not in the store */
636
+ path?: string;
623
637
  /** The field name (last segment of path) */
624
638
  fieldname: string;
625
639
  /** Value before the change */
@@ -630,7 +644,7 @@ export declare interface FieldChangeContext {
630
644
  operation: 'set' | 'delete' | 'patch';
631
645
  /** The doctype of the record being changed */
632
646
  doctype: string;
633
- /** The record ID if applicable */
647
+ /** The record ID; absent for a record not saved yet */
634
648
  recordId?: string;
635
649
  /** Timestamp of the change */
636
650
  timestamp: Date;
@@ -793,8 +807,8 @@ export declare class FieldTriggerEngine {
793
807
  * @public
794
808
  */
795
809
  export declare interface FieldTriggerExecutionResult {
796
- /** The path that triggered the actions */
797
- path: string;
810
+ /** The path that triggered the actions; absent for a record not saved yet */
811
+ path?: string;
798
812
  /** Results for each action that was executed */
799
813
  actionResults: ActionExecutionResult[];
800
814
  /** Total execution time for all actions */
@@ -1849,7 +1863,7 @@ export declare class Stonecrop {
1849
1863
  getSnapshot: () => OperationLogSnapshot;
1850
1864
  markIrreversible: (operationId: string, reason: string) => void;
1851
1865
  logAction: (doctype: string, actionName: string, recordIds?: string[], result?: "success" | "failure" | "pending", error?: string) => string;
1852
- }, "config" | "operations" | "clientId" | "currentIndex">, Pick<{
1866
+ }, "config" | "operations" | "currentIndex" | "clientId">, Pick<{
1853
1867
  operations: Ref< {
1854
1868
  id: string;
1855
1869
  type: HSTOperationType;
@@ -2039,6 +2053,18 @@ export declare class Stonecrop {
2039
2053
  * @param recordData - The record data
2040
2054
  */
2041
2055
  addRecord(doctype: string | Doctype, recordId: string, recordData: any): void;
2056
+ /**
2057
+ * The record a form is editing, read and set by field name; setting a field runs its rules. A
2058
+ * saved record is read and set through the store. A record not saved yet (`recordId` is
2059
+ * {@link DRAFT_RECORD_ID}) is held by the object returned, never in the store, and each call
2060
+ * returns a new one, holding only its starting values.
2061
+ * @param doctype - The doctype
2062
+ * @param recordId - The record ID, or {@link DRAFT_RECORD_ID} for a record not saved yet
2063
+ * @param startingValues - A record not saved yet's values before anything is set, such as
2064
+ * {@link Registry.composeNewRecord} gives; they run no rules. Only a new record takes them.
2065
+ * @returns The record to read and set
2066
+ */
2067
+ editRecord(doctype: string | Doctype, recordId: string, startingValues?: Record<string, unknown>): EditableRecord;
2042
2068
  /**
2043
2069
  * Get a specific record
2044
2070
  * @param doctype - The doctype
@@ -2624,7 +2650,7 @@ getOperationsFor: (doctype: string, recordId?: string) => HSTOperation[];
2624
2650
  getSnapshot: () => OperationLogSnapshot;
2625
2651
  markIrreversible: (operationId: string, reason: string) => void;
2626
2652
  logAction: (doctype: string, actionName: string, recordIds?: string[], result?: "success" | "failure" | "pending", error?: string) => string;
2627
- }, "config" | "operations" | "clientId" | "currentIndex">, Pick<{
2653
+ }, "config" | "operations" | "currentIndex" | "clientId">, Pick<{
2628
2654
  operations: Ref< {
2629
2655
  id: string;
2630
2656
  type: HSTOperationType;
package/dist/stonecrop.js CHANGED
@@ -50,7 +50,7 @@ async function executeClientHandler(code, api = {}) {
50
50
  * mutated it in place — any invalidation discarded the edits silently. Seeding the node instead
51
51
  * makes the draft a phantom row, because `getRecords` lists every key under the doctype.
52
52
  *
53
- * So a draft is held off-HST by whoever renders the form, and reaches the server as an action
53
+ * So a draft is held off-HST, by the record `Stonecrop.editRecord` returns for it, and reaches the server as an action
54
54
  * carrying no record id, which the write path already reads as "create".
55
55
  */
56
56
  /**
@@ -78,6 +78,51 @@ function isDraftRecordId(recordId) {
78
78
  return recordId === "new";
79
79
  }
80
80
  //#endregion
81
+ //#region src/stores/path.ts
82
+ /**
83
+ * Parse a path string into segments, handling both dot notation and array bracket notation
84
+ * @param path - The path string to parse (e.g., "order.456.line_items[0].product")
85
+ * @returns Array of path segments (e.g., ['order', '456', 'line_items', '0', 'product'])
86
+ */
87
+ function parsePath(path) {
88
+ if (!path) return [];
89
+ return path.replace(/\[(\d+)\]/g, ".$1").split(".").filter((segment) => segment.length > 0);
90
+ }
91
+ //#endregion
92
+ //#region src/record-access.ts
93
+ /**
94
+ * A saved record's fields, read and set by name through the store that holds it. A set is a store
95
+ * write, so it runs the rules of the field it sets. A set with no field name throws, rather than
96
+ * reaching the store as a write to the whole record.
97
+ *
98
+ * @param store - the store holding the record
99
+ * @param recordPath - the record's path in that store, `doctype.recordId`
100
+ */
101
+ function recordInStore(store, recordPath) {
102
+ return {
103
+ get: (fieldname) => store.get(fieldname ? `${recordPath}.${fieldname}` : recordPath),
104
+ set: (fieldname, value) => {
105
+ if (parsePath(fieldname).length === 0) throw new Error("Cannot set value on empty path");
106
+ store.set(`${recordPath}.${fieldname}`, value);
107
+ }
108
+ };
109
+ }
110
+ /**
111
+ * For a rule run with no record to reach: `get` and `set` throw the reason, rather than reading
112
+ * nothing and setting nowhere.
113
+ *
114
+ * @param reason - why there is no record
115
+ */
116
+ function noRecord(reason) {
117
+ const refuse = () => {
118
+ throw new Error(reason);
119
+ };
120
+ return {
121
+ get: refuse,
122
+ set: refuse
123
+ };
124
+ }
125
+ //#endregion
81
126
  //#region src/stores/operation-log.ts
82
127
  /**
83
128
  * Generate a UUID using crypto API or fallback
@@ -933,6 +978,7 @@ async function triggerTransition(doctype, transition, options) {
933
978
  doctype,
934
979
  recordId: options?.recordId,
935
980
  timestamp: /* @__PURE__ */ new Date(),
981
+ ...noRecord(`Transition "${transition}" was triggered without a store, so it has no record to read or set`),
936
982
  transition,
937
983
  currentState: options?.currentState,
938
984
  targetState: options?.targetState,
@@ -954,6 +1000,57 @@ function markOperationIrreversible(operationId, reason) {
954
1000
  } catch {}
955
1001
  }
956
1002
  //#endregion
1003
+ //#region src/edit-record.ts
1004
+ function readField(record, fieldname) {
1005
+ return parsePath(fieldname).reduce((value, segment) => value == null ? void 0 : value[segment], record);
1006
+ }
1007
+ function writeField(record, fieldname, value) {
1008
+ const segments = parsePath(fieldname);
1009
+ const last = segments.pop();
1010
+ if (last === void 0) throw new Error("Cannot set value on empty path");
1011
+ let target = record;
1012
+ for (const segment of segments) {
1013
+ target = target[segment];
1014
+ if (target == null) throw new Error(`Cannot set property on null/undefined path: ${fieldname}`);
1015
+ }
1016
+ target[last] = value;
1017
+ }
1018
+ /**
1019
+ * A record not saved yet, held here rather than in the store: a store key for it was tried and failed
1020
+ * (see `DRAFT_RECORD_ID`). Setting a field runs that field's rules, as a store write does for a saved
1021
+ * record, and those rules reach this record through the same `get` and `set`. As in the store, a
1022
+ * set inside a group the record does not have throws.
1023
+ *
1024
+ * @param doctype - the record's doctype slug
1025
+ * @param store - the shared store, handed to rules for reading other records
1026
+ * @param startingValues - the record's values before anything is set; they run no rules
1027
+ */
1028
+ function newRecord(doctype, store, startingValues = {}) {
1029
+ const values = reactive({ ...startingValues });
1030
+ const record = {
1031
+ get: (fieldname) => readField(values, fieldname),
1032
+ set: (fieldname, value) => {
1033
+ const beforeValue = record.get(fieldname);
1034
+ if (Object.is(beforeValue, value)) return;
1035
+ writeField(values, fieldname, value);
1036
+ getGlobalTriggerEngine().executeFieldTriggers({
1037
+ fieldname,
1038
+ beforeValue,
1039
+ afterValue: value,
1040
+ operation: "set",
1041
+ doctype,
1042
+ timestamp: /* @__PURE__ */ new Date(),
1043
+ store,
1044
+ get: (field) => record.get(field),
1045
+ set: (field, fieldValue) => record.set(field, fieldValue)
1046
+ }).catch((error) => {
1047
+ console.warn("Field trigger error:", error instanceof Error ? error.message : error);
1048
+ });
1049
+ }
1050
+ };
1051
+ return record;
1052
+ }
1053
+ //#endregion
957
1054
  //#region src/stores/hst.ts
958
1055
  /**
959
1056
  * Get the operation log store if available
@@ -1079,7 +1176,7 @@ var HSTProxy = class HSTProxy {
1079
1176
  has(path) {
1080
1177
  try {
1081
1178
  if (path === "") return true;
1082
- const segments = this.parsePath(path);
1179
+ const segments = parsePath(path);
1083
1180
  let current = this.target;
1084
1181
  for (let i = 0; i < segments.length; i++) {
1085
1182
  const segment = segments[i];
@@ -1134,6 +1231,7 @@ var HSTProxy = class HSTProxy {
1134
1231
  recordId,
1135
1232
  timestamp: /* @__PURE__ */ new Date(),
1136
1233
  store: this.rootNode || void 0,
1234
+ ...recordId ? recordInStore(this.rootNode ?? this, pathSegments.slice(0, 2).join(".")) : noRecord(`Transition "${transition}" was triggered above any record, so it has no record to read or set`),
1137
1235
  transition,
1138
1236
  currentState: context?.currentState,
1139
1237
  targetState: context?.targetState,
@@ -1164,7 +1262,7 @@ var HSTProxy = class HSTProxy {
1164
1262
  }
1165
1263
  resolveValue(path) {
1166
1264
  if (path === "") return this.target;
1167
- const segments = this.parsePath(path);
1265
+ const segments = parsePath(path);
1168
1266
  let current = this.target;
1169
1267
  for (const segment of segments) {
1170
1268
  if (current === null || current === void 0) return;
@@ -1174,7 +1272,7 @@ var HSTProxy = class HSTProxy {
1174
1272
  }
1175
1273
  updateValue(path, value) {
1176
1274
  if (path === "") throw new Error("Cannot set value on empty path");
1177
- const segments = this.parsePath(path);
1275
+ const segments = parsePath(path);
1178
1276
  const lastSegment = segments.pop();
1179
1277
  let current = this.target;
1180
1278
  for (const segment of segments) {
@@ -1219,7 +1317,8 @@ var HSTProxy = class HSTProxy {
1219
1317
  doctype,
1220
1318
  recordId,
1221
1319
  timestamp: /* @__PURE__ */ new Date(),
1222
- store: this.rootNode || void 0
1320
+ store: this.rootNode || void 0,
1321
+ ...recordInStore(this.rootNode ?? this, pathSegments.slice(0, 2).join("."))
1223
1322
  };
1224
1323
  await triggerEngine.executeFieldTriggers(context);
1225
1324
  } catch (error) {
@@ -1253,15 +1352,6 @@ var HSTProxy = class HSTProxy {
1253
1352
  isPrimitive(value) {
1254
1353
  return value === null || value === void 0 || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "function" || typeof value === "symbol" || typeof value === "bigint";
1255
1354
  }
1256
- /**
1257
- * Parse a path string into segments, handling both dot notation and array bracket notation
1258
- * @param path - The path string to parse (e.g., "order.456.line_items[0].product")
1259
- * @returns Array of path segments (e.g., ['order', '456', 'line_items', '0', 'product'])
1260
- */
1261
- parsePath(path) {
1262
- if (!path) return [];
1263
- return path.replace(/\[(\d+)\]/g, ".$1").split(".").filter((segment) => segment.length > 0);
1264
- }
1265
1355
  };
1266
1356
  /**
1267
1357
  * Factory function for HST creation
@@ -1394,6 +1484,24 @@ var Stonecrop = class Stonecrop {
1394
1484
  this.hstStore.set(`${slug}.${recordId}`, recordData);
1395
1485
  }
1396
1486
  /**
1487
+ * The record a form is editing, read and set by field name; setting a field runs its rules. A
1488
+ * saved record is read and set through the store. A record not saved yet (`recordId` is
1489
+ * {@link DRAFT_RECORD_ID}) is held by the object returned, never in the store, and each call
1490
+ * returns a new one, holding only its starting values.
1491
+ * @param doctype - The doctype
1492
+ * @param recordId - The record ID, or {@link DRAFT_RECORD_ID} for a record not saved yet
1493
+ * @param startingValues - A record not saved yet's values before anything is set, such as
1494
+ * {@link Registry.composeNewRecord} gives; they run no rules. Only a new record takes them.
1495
+ * @returns The record to read and set
1496
+ */
1497
+ editRecord(doctype, recordId, startingValues) {
1498
+ const slug = typeof doctype === "string" ? doctype : doctype.slug;
1499
+ if (isDraftRecordId(recordId)) return newRecord(slug, this.hstStore, startingValues);
1500
+ if (startingValues) throw new Error(`Starting values are only for a new record, not ${slug} ${recordId}`);
1501
+ this.ensureDoctypeExists(slug);
1502
+ return recordInStore(this.hstStore, `${slug}.${recordId}`);
1503
+ }
1504
+ /**
1397
1505
  * Get a specific record
1398
1506
  * @param doctype - The doctype
1399
1507
  * @param recordId - The record ID