@stonecrop/stonecrop 0.41.1 → 0.43.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/README.md CHANGED
@@ -163,6 +163,8 @@ When you pass a string doctype slug instead of a `Doctype` instance, `useStonecr
163
163
  2. If not, call `registry.getMeta` to lazy-load it
164
164
  3. Return `isLoading`, `error`, and `resolvedDoctype` refs for handling the async state
165
165
 
166
+ The same refs cover reading the record: `isLoading` is true while it is fetched, and a failed read sets `error` and leaves `formData` empty, never a blank record in its place. A record the server does not have fails with the code `RECORD_NOT_FOUND`.
167
+
166
168
  ```typescript
167
169
  const { isLoading, error, resolvedDoctype, resolvedSchema, formData } = useStonecrop({
168
170
  doctype: 'plan', // string slug - triggers lazy-loading
@@ -170,7 +172,7 @@ const { isLoading, error, resolvedDoctype, resolvedSchema, formData } = useStone
170
172
  })
171
173
 
172
174
  // In your template:
173
- // <div v-if="isLoading">Loading doctype...</div>
175
+ // <div v-if="isLoading">Loading...</div>
174
176
  // <div v-else-if="error">Error: {{ error.message }}</div>
175
177
  // <AForm v-else :schema="resolvedSchema" v-model:data="formData" />
176
178
  ```
@@ -159,9 +159,9 @@ export declare interface BatchOperation {
159
159
  export declare type ClientHandlerApi = Record<string, unknown>;
160
160
 
161
161
  /**
162
- * Build a new record, once, from every starting value: the schema's empty values, the doctype's `defaults`, then
163
- * the source the app registered for it. Layers apply in that order, so the registered source wins however long
164
- * the doctype's took.
162
+ * Build a new record, once, from every starting value: the doctype's `defaults`, then the source the app registered
163
+ * for it, over the record's tables and embedded records. Layers apply in that order, so the registered source wins
164
+ * however long the doctype's took. A field neither sets has no value, so a save leaves it to the database's default.
165
165
  *
166
166
  * Nothing is returned until every value is in, so nothing is written to the record after a user can see it.
167
167
  * A value that throws, rejects, or has not arrived within `timeoutMs` (default {@link DEFAULTS_TIMEOUT_MS}) is
@@ -1106,13 +1106,14 @@ export declare type HSTStonecropReturn = BaseStonecropReturn & {
1106
1106
  handleHSTChange: (changeData: HSTChangeData) => void;
1107
1107
  };
1108
1108
  /**
1109
- * Loading state for async doctype resolution.
1110
- * True while fetching doctype by slug string from registry.
1109
+ * Loading state: true while a doctype named by slug is resolved, a new record's starting values
1110
+ * are composed, or an existing record is read from the server.
1111
1111
  */
1112
1112
  isLoading: Ref<boolean>;
1113
1113
  /**
1114
- * Error state for doctype resolution failures.
1115
- * Set when doctype slug lookup fails.
1114
+ * Why the form cannot show: the doctype slug did not resolve, or the record read failed. A
1115
+ * record the server does not find carries the code `"RECORD_NOT_FOUND"`. `formData` stays
1116
+ * empty when the read fails.
1116
1117
  */
1117
1118
  error: Ref<Error | null>;
1118
1119
  /**
@@ -1552,15 +1553,18 @@ export declare class Registry {
1552
1553
  */
1553
1554
  private buildTableConfig;
1554
1555
  /**
1555
- * Initialize a new record with default values based on a resolved schema.
1556
+ * The shape of a new record before any starting value: the containers its fields need, and no values.
1556
1557
  * Narrows by `kind` discriminator for precise branch selection.
1557
1558
  *
1558
- * - `kind: 'table'` or `kind: 'link'` → `[]` or `{}`
1559
+ * - `kind: 'table'` → `[]`
1560
+ * - `kind: 'link'` → the embedded record, built the same way
1559
1561
  * - `kind: 'fieldset'` → its children, at the top level of the record: a fieldset is layout
1560
- * - `kind: 'field'` → an empty value for the component's category; falls back to `null`
1562
+ * - `kind: 'field'` → no key at all
1561
1563
  *
1562
- * @param schema - The resolved schema array to derive defaults from
1563
- * @returns A plain object with default values for each field
1564
+ * Starting values are the doctype's `defaults` and the app's, which `composeNewRecord` lays over this.
1565
+ *
1566
+ * @param schema - The resolved schema array to derive the record from
1567
+ * @returns A plain object holding each table and embedded record, and no field values
1564
1568
  * @public
1565
1569
  */
1566
1570
  initializeRecord(schema: ResolvedField[]): Record<string, any>;
@@ -2122,9 +2126,13 @@ export declare class Stonecrop {
2122
2126
  *
2123
2127
  * @param doctype - The doctype slug string or Doctype object
2124
2128
  * @param recordId - The record ID
2129
+ * A record the server does not find is an error, not an empty answer: a caller drawing what is in
2130
+ * HST would otherwise show it as a blank record.
2131
+ *
2125
2132
  * @param options - Query options (includeNested, maxDepth), forwarded to the client
2126
2133
  * @throws Error if no data client has been configured
2127
2134
  * @throws Error if a slug string is given and no matching doctype is found in the registry
2135
+ * @throws Error with code `"RECORD_NOT_FOUND"` if the server returns no record
2128
2136
  * @public
2129
2137
  */
2130
2138
  getRecord(doctype: string | Doctype, recordId: string, options?: GetRecordOptions): Promise<void>;
@@ -2193,9 +2201,8 @@ export declare class Stonecrop {
2193
2201
  */
2194
2202
  collectRecordPayload(doctype: Doctype, recordId: string): Record<string, any>;
2195
2203
  /**
2196
- * Scaffold empty descendant records from defaults for all descendant links.
2197
- *
2198
- * Initializes all scalar and link fields at their HST paths with default values.
2204
+ * Scaffold a new descendant record at `path`: its node, so edits under it land, and its starting values, each at
2205
+ * its own HST path. A field with no starting value gets no path until someone fills it in.
2199
2206
  * For new records, call this after setting up the doctype to ensure all paths exist.
2200
2207
  *
2201
2208
  * @param path - HST path (e.g., "customer.new")
package/dist/stonecrop.js CHANGED
@@ -1544,9 +1544,13 @@ var Stonecrop = class Stonecrop {
1544
1544
  *
1545
1545
  * @param doctype - The doctype slug string or Doctype object
1546
1546
  * @param recordId - The record ID
1547
+ * A record the server does not find is an error, not an empty answer: a caller drawing what is in
1548
+ * HST would otherwise show it as a blank record.
1549
+ *
1547
1550
  * @param options - Query options (includeNested, maxDepth), forwarded to the client
1548
1551
  * @throws Error if no data client has been configured
1549
1552
  * @throws Error if a slug string is given and no matching doctype is found in the registry
1553
+ * @throws Error with code `"RECORD_NOT_FOUND"` if the server returns no record
1550
1554
  * @public
1551
1555
  */
1552
1556
  async getRecord(doctype, recordId, options) {
@@ -1556,7 +1560,8 @@ var Stonecrop = class Stonecrop {
1556
1560
  if (isDraftRecordId(recordId)) return;
1557
1561
  if (this.getRecordById(resolved.slug, recordId)) return;
1558
1562
  const result = await this._client.getRecord(resolved, recordId, options);
1559
- if (result?.record) this.addRecord(resolved, recordId, result.record);
1563
+ if (!result?.record) throw recordNotFound(resolved, recordId);
1564
+ this.addRecord(resolved, recordId, result.record);
1560
1565
  }
1561
1566
  /**
1562
1567
  * Dispatch an action to the server via the configured data client, and file the record it
@@ -1666,9 +1671,8 @@ var Stonecrop = class Stonecrop {
1666
1671
  return payload;
1667
1672
  }
1668
1673
  /**
1669
- * Scaffold empty descendant records from defaults for all descendant links.
1670
- *
1671
- * Initializes all scalar and link fields at their HST paths with default values.
1674
+ * Scaffold a new descendant record at `path`: its node, so edits under it land, and its starting values, each at
1675
+ * its own HST path. A field with no starting value gets no path until someone fills it in.
1672
1676
  * For new records, call this after setting up the doctype to ensure all paths exist.
1673
1677
  *
1674
1678
  * @param path - HST path (e.g., "customer.new")
@@ -1699,7 +1703,7 @@ var Stonecrop = class Stonecrop {
1699
1703
  async fetchNestedData(path, doctype, recordId, options) {
1700
1704
  if (!this._client) throw createCodedError("No data client configured. Call setClient() with a DataClient implementation (e.g., StonecropClient from @stonecrop/graphql-client) before fetching records.", "CLIENT_REQUIRED");
1701
1705
  const result = await this._client.getRecord({ name: doctype.doctype }, recordId, { includeNested: options?.includeNested ?? true });
1702
- if (!result?.record) throw createCodedError(`Record not found: ${doctype.doctype} ${recordId}`, "RECORD_NOT_FOUND");
1706
+ if (!result?.record) throw recordNotFound(doctype, recordId);
1703
1707
  const slug = doctype.slug;
1704
1708
  this.ensureDoctypeExists(slug);
1705
1709
  if (!this.hstStore.get(`${slug}.${recordId}`)) this.hstStore.set(`${slug}.${recordId}`, {}, "system");
@@ -1733,6 +1737,10 @@ function createCodedError(message, code) {
1733
1737
  error.code = code;
1734
1738
  return error;
1735
1739
  }
1740
+ /** The one error both record reads throw when the server returns no record. */
1741
+ function recordNotFound(doctype, recordId) {
1742
+ return createCodedError(`Record not found: ${doctype.doctype} ${recordId}`, "RECORD_NOT_FOUND");
1743
+ }
1736
1744
  //#endregion
1737
1745
  //#region src/composables/stonecrop.ts
1738
1746
  /**
@@ -1837,6 +1845,25 @@ function useStonecrop(options) {
1837
1845
  }
1838
1846
  if (hstStore.value) setupDeepReactivity(options.doctype, options.recordId || "new", formData, hstStore.value);
1839
1847
  }
1848
+ const loadExistingRecord = async (doctype, recordId) => {
1849
+ if (!stonecrop.value) return;
1850
+ const existingRecord = stonecrop.value.getRecordById(doctype, recordId);
1851
+ if (existingRecord) {
1852
+ formData.value = existingRecord.get("") || {};
1853
+ return;
1854
+ }
1855
+ if (!stonecrop.value.getClient()) return;
1856
+ isLoading.value = true;
1857
+ error.value = null;
1858
+ try {
1859
+ await stonecrop.value.getRecord(doctype, recordId);
1860
+ formData.value = stonecrop.value.getRecordById(doctype, recordId)?.get("") || {};
1861
+ } catch (e) {
1862
+ error.value = e instanceof Error ? e : new Error(String(e));
1863
+ } finally {
1864
+ isLoading.value = false;
1865
+ }
1866
+ };
1840
1867
  onMounted(async () => {
1841
1868
  if (!registry || !stonecrop.value) return;
1842
1869
  if (options.doctype) {
@@ -1866,17 +1893,8 @@ function useStonecrop(options) {
1866
1893
  resolvedDoctype.value = doctype;
1867
1894
  if (!doctype) return;
1868
1895
  resolvedSchema.value = registry.resolveSchema(doctype);
1869
- if (recordId && !isDraftRecordId(recordId)) {
1870
- const existingRecord = stonecrop.value.getRecordById(doctype, recordId);
1871
- if (existingRecord) formData.value = existingRecord.get("") || {};
1872
- else try {
1873
- await stonecrop.value.getRecord(doctype, recordId);
1874
- const loadedRecord = stonecrop.value.getRecordById(doctype, recordId);
1875
- if (loadedRecord) formData.value = loadedRecord.get("") || {};
1876
- } catch {
1877
- formData.value = registry.initializeRecord(resolvedSchema.value);
1878
- }
1879
- } else {
1896
+ if (recordId && !isDraftRecordId(recordId)) await loadExistingRecord(doctype, recordId);
1897
+ else {
1880
1898
  isLoading.value = true;
1881
1899
  try {
1882
1900
  formData.value = (await registry.composeNewRecord(doctype)).record;
@@ -1885,18 +1903,7 @@ function useStonecrop(options) {
1885
1903
  }
1886
1904
  }
1887
1905
  if (hstStore.value) setupDeepReactivity(doctype, recordId || "new", formData, hstStore.value);
1888
- } else if (recordId && !isDraftRecordId(recordId)) {
1889
- const doctype = options.doctype;
1890
- const existingRecord = stonecrop.value.getRecordById(doctype, recordId);
1891
- if (existingRecord) formData.value = existingRecord.get("") || {};
1892
- else try {
1893
- await stonecrop.value.getRecord(doctype, recordId);
1894
- const loadedRecord = stonecrop.value.getRecordById(doctype, recordId);
1895
- if (loadedRecord) formData.value = loadedRecord.get("") || {};
1896
- } catch {
1897
- formData.value = registry.initializeRecord(resolvedSchema.value);
1898
- }
1899
- }
1906
+ } else if (recordId && !isDraftRecordId(recordId)) await loadExistingRecord(options.doctype, recordId);
1900
1907
  }
1901
1908
  });
1902
1909
  const provideHSTPath = (fieldname, customRecordId) => {
@@ -3026,19 +3033,13 @@ async function applyDoctypeDefaults(target, doctype, run, path, within) {
3026
3033
  await applyLayer(target, doctype.defaults, fields, run, path, [...within, doctype]);
3027
3034
  }
3028
3035
  /**
3029
- * One row of a table's starting value: the row's own empty values and its doctype's `defaults`, then the row's
3030
- * entries. A linked table's rows are records of its target doctype; an inline table's rows have one value per
3031
- * column.
3036
+ * One row of a table's starting value: its doctype's `defaults`, then the row's entries. A linked table's rows are
3037
+ * records of its target doctype; an inline table's rows have no doctype, so they hold only their entries.
3032
3038
  */
3033
3039
  async function composeRow(row, table, run, path, within) {
3034
3040
  const { registry, now } = run;
3035
3041
  const fields = table.holds === "rows" ? recordFields(registry, table.target) : columnFields(table.columns);
3036
- const floor = table.holds === "rows" ? registry.initializeRecord(registry.resolveSchema(table.target)) : registry.initializeRecord(table.columns.map((column) => ({
3037
- kind: "field",
3038
- fieldname: column.fieldname,
3039
- component: column.component ?? "ATextInput",
3040
- label: column.label
3041
- })));
3042
+ const floor = table.holds === "rows" ? registry.initializeRecord(registry.resolveSchema(table.target)) : {};
3042
3043
  if (table.holds === "rows") await applyDoctypeDefaults(floor, table.target, run, `${path} defaults`, within);
3043
3044
  const rowRecord = resolveTokensInRecord(floor, fields, registry, now);
3044
3045
  if (!isDefaultsDocument(row)) {
@@ -3063,9 +3064,9 @@ async function applyLayer(target, layer, fields, run, path, within) {
3063
3064
  await applyDocument(target, evaluated.value, fields, run, path, within);
3064
3065
  }
3065
3066
  /**
3066
- * Build a new record, once, from every starting value: the schema's empty values, the doctype's `defaults`, then
3067
- * the source the app registered for it. Layers apply in that order, so the registered source wins however long
3068
- * the doctype's took.
3067
+ * Build a new record, once, from every starting value: the doctype's `defaults`, then the source the app registered
3068
+ * for it, over the record's tables and embedded records. Layers apply in that order, so the registered source wins
3069
+ * however long the doctype's took. A field neither sets has no value, so a save leaves it to the database's default.
3069
3070
  *
3070
3071
  * Nothing is returned until every value is in, so nothing is written to the record after a user can see it.
3071
3072
  * A value that throws, rejects, or has not arrived within `timeoutMs` (default {@link DEFAULTS_TIMEOUT_MS}) is
@@ -3300,15 +3301,18 @@ var Registry = class Registry {
3300
3301
  };
3301
3302
  }
3302
3303
  /**
3303
- * Initialize a new record with default values based on a resolved schema.
3304
+ * The shape of a new record before any starting value: the containers its fields need, and no values.
3304
3305
  * Narrows by `kind` discriminator for precise branch selection.
3305
3306
  *
3306
- * - `kind: 'table'` or `kind: 'link'` → `[]` or `{}`
3307
+ * - `kind: 'table'` → `[]`
3308
+ * - `kind: 'link'` → the embedded record, built the same way
3307
3309
  * - `kind: 'fieldset'` → its children, at the top level of the record: a fieldset is layout
3308
- * - `kind: 'field'` → an empty value for the component's category; falls back to `null`
3310
+ * - `kind: 'field'` → no key at all
3311
+ *
3312
+ * Starting values are the doctype's `defaults` and the app's, which `composeNewRecord` lays over this.
3309
3313
  *
3310
- * @param schema - The resolved schema array to derive defaults from
3311
- * @returns A plain object with default values for each field
3314
+ * @param schema - The resolved schema array to derive the record from
3315
+ * @returns A plain object holding each table and embedded record, and no field values
3312
3316
  * @public
3313
3317
  */
3314
3318
  initializeRecord(schema) {
@@ -3316,14 +3320,6 @@ var Registry = class Registry {
3316
3320
  for (const field of schema) if (field.kind === "table") record[field.fieldname] = [];
3317
3321
  else if (field.kind === "link") record[field.fieldname] = this.initializeRecord(field.schema);
3318
3322
  else if (field.kind === "fieldset") Object.assign(record, this.initializeRecord(field.schema));
3319
- else {
3320
- const category = componentCategory(field.component);
3321
- if (category === "text") record[field.fieldname] = "";
3322
- else if (category === "number") record[field.fieldname] = 0;
3323
- else if (category === "boolean") record[field.fieldname] = false;
3324
- else if (category === "code" && field.language) record[field.fieldname] = field.language === "json" ? {} : "";
3325
- else record[field.fieldname] = null;
3326
- }
3327
3323
  return record;
3328
3324
  }
3329
3325
  /**