@verikit/ui-core 0.23.1

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.md ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Chidi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,7 @@
1
+ export { firstFieldError, firstFieldErrors, inferAndValidateResource, omitFieldError, submitVerikitActionForm, submitVerikitResourceForm, validationIssuesToFieldErrors, } from "./submission.js";
2
+ export type { SubmitVerikitActionFormOptions, SubmitVerikitResourceFormOptions, VerikitActionSubmitResult, VerikitFieldErrors, VerikitFormFields, VerikitFormValues, VerikitResourceSubmitResult, VerikitResourceSubmitSuccess, VerikitValidationFailure, } from "./submission.js";
3
+ export { inferAndValidateSchemaTree, submitVerikitSchemaTreeActionForm, submitVerikitSchemaTreeForm, } from "./schema-tree.js";
4
+ export type { SubmitVerikitSchemaTreeActionFormOptions, SubmitVerikitSchemaTreeFormOptions, } from "./schema-tree.js";
5
+ export { isResource, resolveVerikitFields } from "./resolve-fields.js";
6
+ export type { VerikitFormSource } from "./resolve-fields.js";
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/form/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,eAAe,EACf,gBAAgB,EAChB,wBAAwB,EACxB,cAAc,EACd,uBAAuB,EACvB,yBAAyB,EACzB,6BAA6B,GAC9B,MAAM,iBAAiB,CAAC;AACzB,YAAY,EACV,8BAA8B,EAC9B,gCAAgC,EAChC,yBAAyB,EACzB,kBAAkB,EAClB,iBAAiB,EACjB,iBAAiB,EACjB,2BAA2B,EAC3B,4BAA4B,EAC5B,wBAAwB,GACzB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,0BAA0B,EAC1B,iCAAiC,EACjC,2BAA2B,GAC5B,MAAM,kBAAkB,CAAC;AAC1B,YAAY,EACV,wCAAwC,EACxC,kCAAkC,GACnC,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,UAAU,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AACvE,YAAY,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC"}
@@ -0,0 +1,3 @@
1
+ export { firstFieldError, firstFieldErrors, inferAndValidateResource, omitFieldError, submitVerikitActionForm, submitVerikitResourceForm, validationIssuesToFieldErrors, } from "./submission.js";
2
+ export { inferAndValidateSchemaTree, submitVerikitSchemaTreeActionForm, submitVerikitSchemaTreeForm, } from "./schema-tree.js";
3
+ export { isResource, resolveVerikitFields } from "./resolve-fields.js";
@@ -0,0 +1,9 @@
1
+ import type { Resource, ResourceSchema } from "@verikit/core";
2
+ import type { VerikitFormFields } from "./submission.js";
3
+ /** Source accepted by a flat Verikit form: a field map, a resource builder, or its schema. */
4
+ export type VerikitFormSource = VerikitFormFields | Resource | ResourceSchema;
5
+ /** Returns true when a source is a resource builder. */
6
+ export declare function isResource(value: VerikitFormSource): value is Resource;
7
+ /** Resolves any supported form source into a field schema map. */
8
+ export declare function resolveVerikitFields(source: VerikitFormSource): VerikitFormFields;
9
+ //# sourceMappingURL=resolve-fields.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolve-fields.d.ts","sourceRoot":"","sources":["../../src/form/resolve-fields.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC9D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAEzD,8FAA8F;AAC9F,MAAM,MAAM,iBAAiB,GAAG,iBAAiB,GAAG,QAAQ,GAAG,cAAc,CAAC;AAE9E,wDAAwD;AACxD,wBAAgB,UAAU,CAAC,KAAK,EAAE,iBAAiB,GAAG,KAAK,IAAI,QAAQ,CAEtE;AAMD,kEAAkE;AAClE,wBAAgB,oBAAoB,CAClC,MAAM,EAAE,iBAAiB,GACxB,iBAAiB,CAUnB"}
@@ -0,0 +1,17 @@
1
+ /** Returns true when a source is a resource builder. */
2
+ export function isResource(value) {
3
+ return typeof value.toSchema === "function";
4
+ }
5
+ function isResourceSchema(value) {
6
+ return value.type === "resource";
7
+ }
8
+ /** Resolves any supported form source into a field schema map. */
9
+ export function resolveVerikitFields(source) {
10
+ if (isResource(source)) {
11
+ return source.toSchema().fields;
12
+ }
13
+ if (isResourceSchema(source)) {
14
+ return source.fields;
15
+ }
16
+ return source;
17
+ }
@@ -0,0 +1,41 @@
1
+ import { type SchemaNode, type ValidationResult } from "@verikit/core";
2
+ import { type ActionBuilder, type ActionFormMap, type ActionRunRequest } from "@verikit/runtime";
3
+ import { type SchemaPath } from "../layout/path.js";
4
+ import { type VerikitActionSubmitResult, VerikitFormValues, VerikitResourceSubmitResult } from "./submission.js";
5
+ /**
6
+ * Options for inferring, validating, and submitting schema tree form values.
7
+ */
8
+ export interface SubmitVerikitSchemaTreeFormOptions<TResult = unknown> {
9
+ /** Schema nodes that describe the rendered form tree. */
10
+ tree: readonly SchemaNode[];
11
+ /** Raw form values keyed by schema path. */
12
+ values: VerikitFormValues;
13
+ /** Optional callback invoked with inferred and validated values. */
14
+ onSubmit?: (values: VerikitFormValues) => TResult | Promise<TResult>;
15
+ }
16
+ /** Options for submitting an action form from schema tree values. */
17
+ export interface SubmitVerikitSchemaTreeActionFormOptions<TName extends string = string, TForm extends ActionFormMap = ActionFormMap, TContext = unknown, TRecord = unknown, TResult = unknown> {
18
+ /** Runtime action whose form should infer, validate, and execute. */
19
+ action: ActionBuilder<TName, TForm, TContext, TRecord, TResult>;
20
+ /**
21
+ * Action request without input; inferred tree values are supplied as input.
22
+ */
23
+ request: Omit<ActionRunRequest<TContext, TRecord>, "input">;
24
+ /** Schema tree form values containing the action input at `path`. */
25
+ values: VerikitFormValues;
26
+ /** Path to the action input values. Defaults to the action name. */
27
+ path?: SchemaPath;
28
+ }
29
+ /**
30
+ * Infers, validates, and submits values for fields nested in a schema tree.
31
+ */
32
+ export declare function submitVerikitSchemaTreeForm<TResult = undefined>({ tree, values, onSubmit, }: SubmitVerikitSchemaTreeFormOptions<TResult>): Promise<VerikitResourceSubmitResult<TResult | undefined>>;
33
+ /**
34
+ * Infers and validates schema tree values without calling a submit callback.
35
+ */
36
+ export declare function inferAndValidateSchemaTree(tree: readonly SchemaNode[], values: VerikitFormValues): Promise<ValidationResult<VerikitFormValues>>;
37
+ /**
38
+ * Extracts nested action input values from a schema tree and runs the action.
39
+ */
40
+ export declare function submitVerikitSchemaTreeActionForm<TName extends string = string, TForm extends ActionFormMap = ActionFormMap, TContext = unknown, TRecord = unknown, TResult = unknown>({ action, request, values, path, }: SubmitVerikitSchemaTreeActionFormOptions<TName, TForm, TContext, TRecord, TResult>): Promise<VerikitActionSubmitResult<TResult>>;
41
+ //# sourceMappingURL=schema-tree.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema-tree.d.ts","sourceRoot":"","sources":["../../src/form/schema-tree.ts"],"names":[],"mappings":"AAAA,OAAO,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CAAC,OAAO,CAAC,GAAG,OAAO,CACtD,2BAA2B,CAAC,OAAO,GAAG,SAAS,CAAC,CACjD,CAqDA;AAED;;GAEG;AACH,wBAAsB,0BAA0B,CAC9C,IAAI,EAAE,SAAS,UAAU,EAAE,EAC3B,MAAM,EAAE,iBAAiB,GACxB,OAAO,CAAC,gBAAgB,CAAC,iBAAiB,CAAC,CAAC,CAM9C;AAED;;GAEG;AACH,wBAAsB,iCAAiC,CACrD,KAAK,SAAS,MAAM,GAAG,MAAM,EAC7B,KAAK,SAAS,aAAa,GAAG,aAAa,EAC3C,QAAQ,GAAG,OAAO,EAClB,OAAO,GAAG,OAAO,EACjB,OAAO,GAAG,OAAO,EACjB,EACA,MAAM,EACN,OAAO,EACP,MAAM,EACN,IAAoB,GACrB,EAAE,wCAAwC,CACzC,KAAK,EACL,KAAK,EACL,QAAQ,EACR,OAAO,EACP,OAAO,CACR,GAAG,OAAO,CAAC,yBAAyB,CAAC,OAAO,CAAC,CAAC,CAW9C"}
@@ -0,0 +1,151 @@
1
+ import { shouldValidateField, validateFieldAsync, } from "@verikit/core";
2
+ import { inferField, } from "@verikit/runtime";
3
+ import { getValueAtPath, pathKey, setValueAtPath, unsetValueAtPath, } from "../layout/path.js";
4
+ import { submitVerikitActionForm, } from "./submission.js";
5
+ function collectTreeFields(nodes, values, path) {
6
+ return nodes.flatMap((node) => {
7
+ switch (node.type) {
8
+ case "field":
9
+ return [{ path: [...path, node.name], field: node }];
10
+ case "relationship":
11
+ case "action":
12
+ return [];
13
+ case "section":
14
+ case "grid":
15
+ return collectTreeFields(node.children, values, path);
16
+ case "tabs":
17
+ return node.tabs.flatMap((tab) => collectTreeFields(tab.children, values, path));
18
+ case "wizard":
19
+ return node.steps.flatMap((step) => collectTreeFields(step.children, values, path));
20
+ case "repeater": {
21
+ const repeaterPath = [...path, node.name];
22
+ const items = getValueAtPath(values, repeaterPath);
23
+ const rows = Array.isArray(items) ? items : [];
24
+ return rows.flatMap((_, index) => collectTreeFields(node.children, values, [...repeaterPath, index]));
25
+ }
26
+ }
27
+ });
28
+ }
29
+ /**
30
+ * Returns the parent object containing `path` and its sibling values,
31
+ * or `{}` when the parent is missing or not a plain object.
32
+ */
33
+ function siblingValues(path, values) {
34
+ const parent = getValueAtPath(values, path.slice(0, -1));
35
+ return typeof parent === "object" && parent !== null && !Array.isArray(parent)
36
+ ? parent
37
+ : {};
38
+ }
39
+ function shouldValidateTreeField(field, path, values) {
40
+ const key = String(path[path.length - 1]);
41
+ return shouldValidateField(key, field, siblingValues(path, values));
42
+ }
43
+ /**
44
+ * Collects fields eligible for inference and validation and tracks
45
+ * read-only paths so their values can be removed before submission.
46
+ */
47
+ function partitionTreeFields(tree, values) {
48
+ const all = collectTreeFields(tree, values, []);
49
+ return {
50
+ entries: all
51
+ .filter((entry) => !entry.field.readOnly)
52
+ .filter((entry) => shouldValidateTreeField(entry.field, entry.path, values)),
53
+ readOnlyPaths: all
54
+ .filter((entry) => entry.field.readOnly)
55
+ .map((entry) => entry.path),
56
+ };
57
+ }
58
+ function treeFieldErrors(entries) {
59
+ const errors = {};
60
+ for (const { path, result } of entries) {
61
+ if (result.success) {
62
+ continue;
63
+ }
64
+ const key = pathKey(path);
65
+ errors[key] = [
66
+ ...(errors[key] ?? []),
67
+ ...result.issues.map((issue) => issue.message),
68
+ ];
69
+ }
70
+ return errors;
71
+ }
72
+ function treeFieldIssues(entries) {
73
+ return entries.flatMap(({ path, result }) => result.success
74
+ ? []
75
+ : result.issues.map((issue) => ({
76
+ path: [...path, ...issue.path],
77
+ message: issue.message,
78
+ })));
79
+ }
80
+ /**
81
+ * Writes each entry's value at its path. Callers must have already confirmed every entry succeeded.
82
+ */
83
+ function applySuccessfulResults(base, entries) {
84
+ return entries.reduce((values, { path, result }) => setValueAtPath(values, path, result.value), base);
85
+ }
86
+ /**
87
+ * Infers, validates, and submits values for fields nested in a schema tree.
88
+ */
89
+ export async function submitVerikitSchemaTreeForm({ tree, values, onSubmit, }) {
90
+ const { entries, readOnlyPaths } = partitionTreeFields(tree, values);
91
+ const inferred = entries.map(({ path, field }) => ({
92
+ path,
93
+ field,
94
+ result: inferField(field, getValueAtPath(values, path)),
95
+ }));
96
+ if (inferred.some(({ result }) => !result.success)) {
97
+ return {
98
+ success: false,
99
+ reason: "inference",
100
+ issues: treeFieldIssues(inferred),
101
+ fieldErrors: treeFieldErrors(inferred),
102
+ };
103
+ }
104
+ const inferredValues = applySuccessfulResults(values, inferred);
105
+ const validated = await Promise.all(inferred.map(async ({ path, field, result }) => ({
106
+ path,
107
+ result: await validateFieldAsync(field, result.value),
108
+ })));
109
+ if (validated.some(({ result }) => !result.success)) {
110
+ return {
111
+ success: false,
112
+ reason: "validation",
113
+ issues: treeFieldIssues(validated),
114
+ fieldErrors: treeFieldErrors(validated),
115
+ };
116
+ }
117
+ const validatedValues = applySuccessfulResults(inferredValues, validated);
118
+ // A genuine key removal, not merely clearing to `undefined`: this result's
119
+ // `value` can be spread over other data downstream (e.g. an optimistic
120
+ // cache merge), where a present-but-`undefined` key would wrongly clobber
121
+ // an existing value instead of leaving it untouched.
122
+ const finalValues = readOnlyPaths.reduce((current, path) => unsetValueAtPath(current, path), validatedValues);
123
+ return {
124
+ success: true,
125
+ value: finalValues,
126
+ result: await onSubmit?.(finalValues),
127
+ fieldErrors: {},
128
+ };
129
+ }
130
+ /**
131
+ * Infers and validates schema tree values without calling a submit callback.
132
+ */
133
+ export async function inferAndValidateSchemaTree(tree, values) {
134
+ const result = await submitVerikitSchemaTreeForm({ tree, values });
135
+ return result.success
136
+ ? { success: true, value: result.value }
137
+ : { success: false, issues: result.issues };
138
+ }
139
+ /**
140
+ * Extracts nested action input values from a schema tree and runs the action.
141
+ */
142
+ export async function submitVerikitSchemaTreeActionForm({ action, request, values, path = [action.name], }) {
143
+ const actionValues = getValueAtPath(values, path);
144
+ return submitVerikitActionForm({
145
+ action,
146
+ request,
147
+ values: typeof actionValues === "object" && actionValues !== null
148
+ ? actionValues
149
+ : {},
150
+ });
151
+ }
@@ -0,0 +1,75 @@
1
+ import { type FieldSchema, type ValidationIssue, type ValidationResult } from "@verikit/core";
2
+ import { type ActionBuilder, type ActionFormMap, type ActionRunRequest, type ActionRunResult } from "@verikit/runtime";
3
+ /** Plain form values keyed by Verikit field name. */
4
+ export type VerikitFormValues = Record<string, unknown>;
5
+ /** Validation messages keyed by field name or form-level key. */
6
+ export type VerikitFieldErrors = Record<string, string[]>;
7
+ /** Verikit field schema map keyed by field name. */
8
+ export type VerikitFormFields = Record<string, FieldSchema>;
9
+ /** Failed inference or validation result with issues mapped to fields. */
10
+ export interface VerikitValidationFailure {
11
+ /** Marks the result as failed. */
12
+ success: false;
13
+ /** Stage that produced the failure. */
14
+ reason: "inference" | "validation";
15
+ /** Validation issues returned by Verikit. */
16
+ issues: ValidationIssue[];
17
+ /** Issues grouped by field key for UI rendering. */
18
+ fieldErrors: VerikitFieldErrors;
19
+ }
20
+ /** Successful resource form submission result. */
21
+ export interface VerikitResourceSubmitSuccess<TResult = unknown> {
22
+ /** Marks the result as successful. */
23
+ success: true;
24
+ /** Inferred and validated values. */
25
+ value: VerikitFormValues;
26
+ /** Value returned by the submit callback. */
27
+ result: TResult;
28
+ /** Empty field error map for successful submissions. */
29
+ fieldErrors: VerikitFieldErrors;
30
+ }
31
+ /** Result returned when submitting a resource-backed form. */
32
+ export type VerikitResourceSubmitResult<TResult = unknown> = VerikitResourceSubmitSuccess<TResult> | VerikitValidationFailure;
33
+ /** Result returned when submitting an action-backed form. */
34
+ export type VerikitActionSubmitResult<TResult = unknown> = (ActionRunResult<TResult> & {
35
+ fieldErrors: VerikitFieldErrors;
36
+ }) | VerikitValidationFailure;
37
+ /**
38
+ * Options for inferring, validating, and optionally submitting a resource form.
39
+ */
40
+ export interface SubmitVerikitResourceFormOptions<TResult = unknown> {
41
+ /** Field schema map used for inference and validation. */
42
+ fields: VerikitFormFields;
43
+ /** Raw form values to submit. */
44
+ values: VerikitFormValues;
45
+ /** Optional callback invoked with inferred and validated values. */
46
+ onSubmit?: (values: VerikitFormValues) => TResult | Promise<TResult>;
47
+ }
48
+ /** Options for inferring values and running a Verikit action. */
49
+ export interface SubmitVerikitActionFormOptions<TForm extends ActionFormMap = ActionFormMap, TContext = unknown, TRecord = unknown, TResult = unknown> {
50
+ /** Action whose runtime form and handler should be used. */
51
+ action: ActionBuilder<string, TForm, TContext, TRecord, TResult>;
52
+ /** Action request without input; inferred values are supplied as input. */
53
+ request: Omit<ActionRunRequest<TContext, TRecord>, "input">;
54
+ /** Raw form values to infer before running the action. */
55
+ values: VerikitFormValues;
56
+ }
57
+ /**
58
+ * Groups validation issues by their first path segment for field rendering.
59
+ */
60
+ export declare function validationIssuesToFieldErrors(issues: readonly ValidationIssue[]): VerikitFieldErrors;
61
+ /** Returns the first error message for a field, if present. */
62
+ export declare function firstFieldError(fieldErrors: VerikitFieldErrors, name: string): string | undefined;
63
+ /** Collapses each key's error list down to its first message. */
64
+ export declare function firstFieldErrors(fieldErrors: VerikitFieldErrors): Record<string, string>;
65
+ /** Returns a copy of `fieldErrors` with `name`'s entry removed. */
66
+ export declare function omitFieldError(fieldErrors: VerikitFieldErrors, name: string): VerikitFieldErrors;
67
+ /** Infers raw values and validates the inferred resource values. */
68
+ export declare function inferAndValidateResource(fields: VerikitFormFields, values: VerikitFormValues): Promise<ValidationResult<VerikitFormValues>>;
69
+ /** Infers, validates, and submits a resource-backed form. */
70
+ export declare function submitVerikitResourceForm<TResult = undefined>({ fields, values, onSubmit, }: SubmitVerikitResourceFormOptions<TResult>): Promise<VerikitResourceSubmitResult<TResult | undefined>>;
71
+ /**
72
+ * Infers action input values and runs the action with mapped field errors.
73
+ */
74
+ export declare function submitVerikitActionForm<TForm extends ActionFormMap = ActionFormMap, TContext = unknown, TRecord = unknown, TResult = unknown>({ action, request, values, }: SubmitVerikitActionFormOptions<TForm, TContext, TRecord, TResult>): Promise<VerikitActionSubmitResult<TResult>>;
75
+ //# sourceMappingURL=submission.d.ts.map
@@ -0,0 +1 @@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AE,MAAM,GACX,kBAAkB,CAGpB;AAqBD,oEAAoE;AACpE,wBAAsB,wBAAwB,CAC5C,MAAM,EAAE,iBAAiB,EACzB,MAAM,EAAE,iBAAiB,GACxB,OAAO,CAAC,gBAAgB,CAAC,iBAAiB,CAAC,CAAC,CAS9C;AAED,6DAA6D;AAC7D,wBAAsB,yBAAyB,CAAC,OAAO,GAAG,SAAS,EAAE,EACnE,MAAM,EACN,MAAM,EACN,QAAQ,GACT,EAAE,gCAAgC,CAAC,OAAO,CAAC,GAAG,OAAO,CACpD,2BAA2B,CAAC,OAAO,GAAG,SAAS,CAAC,CACjD,CA8BA;AAED;;GAEG;AACH,wBAAsB,uBAAuB,CAC3C,KAAK,SAAS,aAAa,GAAG,aAAa,EAC3C,QAAQ,GAAG,OAAO,EAClB,OAAO,GAAG,OAAO,EACjB,OAAO,GAAG,OAAO,EACjB,EACA,MAAM,EACN,OAAO,EACP,MAAM,GACP,EAAE,8BAA8B,CAAC,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,OAAO,CAAC,GAAG,OAAO,CAC5E,yBAAyB,CAAC,OAAO,CAAC,CACnC,CAiCA"}
@@ -0,0 +1,111 @@
1
+ import { validateResourceAsync, } from "@verikit/core";
2
+ import { inferResource, runAction, } from "@verikit/runtime";
3
+ /**
4
+ * Groups validation issues by their first path segment for field rendering.
5
+ */
6
+ export function validationIssuesToFieldErrors(issues) {
7
+ const errors = {};
8
+ for (const issue of issues) {
9
+ const [fieldName] = issue.path;
10
+ const key = typeof fieldName === "string" || typeof fieldName === "number"
11
+ ? String(fieldName)
12
+ : "$form";
13
+ errors[key] = [...(errors[key] ?? []), issue.message];
14
+ }
15
+ return errors;
16
+ }
17
+ /** Returns the first error message for a field, if present. */
18
+ export function firstFieldError(fieldErrors, name) {
19
+ return fieldErrors[name]?.[0];
20
+ }
21
+ /** Collapses each key's error list down to its first message. */
22
+ export function firstFieldErrors(fieldErrors) {
23
+ return Object.fromEntries(Object.entries(fieldErrors).map(([key, messages]) => [key, messages[0]]));
24
+ }
25
+ /** Returns a copy of `fieldErrors` with `name`'s entry removed. */
26
+ export function omitFieldError(fieldErrors, name) {
27
+ const { [name]: _removed, ...remaining } = fieldErrors;
28
+ return remaining;
29
+ }
30
+ /**
31
+ * A field marked `.readOnly()` is always excluded from create/update
32
+ * submissions, regardless of write permissions. See `FieldSchema.readOnly`.
33
+ * A field marked `.formHidden()` never appears in the form UI either, so it
34
+ * can't have a value for the user to submit. See `FieldSchema.formHidden`.
35
+ *
36
+ * Both are filtered out before inference and validation so that a
37
+ * `required()` read-only or form-hidden field (such as a server-computed
38
+ * display value) does not block a submission that will never include that
39
+ * field.
40
+ */
41
+ function writableFields(fields) {
42
+ return Object.fromEntries(Object.entries(fields).filter(([, schema]) => !schema.readOnly && !schema.formHidden));
43
+ }
44
+ /** Infers raw values and validates the inferred resource values. */
45
+ export async function inferAndValidateResource(fields, values) {
46
+ const relevantFields = writableFields(fields);
47
+ const inferred = inferResource(relevantFields, values);
48
+ if (!inferred.success) {
49
+ return inferred;
50
+ }
51
+ return validateResourceAsync(relevantFields, inferred.value);
52
+ }
53
+ /** Infers, validates, and submits a resource-backed form. */
54
+ export async function submitVerikitResourceForm({ fields, values, onSubmit, }) {
55
+ const relevantFields = writableFields(fields);
56
+ const inferred = inferResource(relevantFields, values);
57
+ if (!inferred.success) {
58
+ return {
59
+ success: false,
60
+ reason: "inference",
61
+ issues: inferred.issues,
62
+ fieldErrors: validationIssuesToFieldErrors(inferred.issues),
63
+ };
64
+ }
65
+ const validated = await validateResourceAsync(relevantFields, inferred.value);
66
+ if (!validated.success) {
67
+ return {
68
+ success: false,
69
+ reason: "validation",
70
+ issues: validated.issues,
71
+ fieldErrors: validationIssuesToFieldErrors(validated.issues),
72
+ };
73
+ }
74
+ return {
75
+ success: true,
76
+ value: validated.value,
77
+ result: await onSubmit?.(validated.value),
78
+ fieldErrors: {},
79
+ };
80
+ }
81
+ /**
82
+ * Infers action input values and runs the action with mapped field errors.
83
+ */
84
+ export async function submitVerikitActionForm({ action, request, values, }) {
85
+ const form = action.getRuntime().form;
86
+ const fields = form
87
+ ? Object.fromEntries(Object.entries(form).map(([name, field]) => [
88
+ name,
89
+ field.toSchema(name),
90
+ ]))
91
+ : {};
92
+ const inferred = inferResource(fields, values);
93
+ if (!inferred.success) {
94
+ return {
95
+ success: false,
96
+ reason: "inference",
97
+ issues: inferred.issues,
98
+ fieldErrors: validationIssuesToFieldErrors(inferred.issues),
99
+ };
100
+ }
101
+ const result = await runAction(action, {
102
+ ...request,
103
+ input: inferred.value,
104
+ });
105
+ return {
106
+ ...result,
107
+ fieldErrors: result.success === false && result.reason === "validation"
108
+ ? validationIssuesToFieldErrors(result.issues)
109
+ : {},
110
+ };
111
+ }
@@ -0,0 +1,4 @@
1
+ export * from "./form/index.js";
2
+ export * from "./layout/index.js";
3
+ export * from "./query/index.js";
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAC;AAChC,cAAc,mBAAmB,CAAC;AAClC,cAAc,kBAAkB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export * from "./form/index.js";
2
+ export * from "./layout/index.js";
3
+ export * from "./query/index.js";
@@ -0,0 +1,3 @@
1
+ export { getValueAtPath, hasValueAtPath, pathKey, setValueAtPath, unsetValueAtPath, } from "./path.js";
2
+ export type { SchemaPath } from "./path.js";
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/layout/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,cAAc,EACd,OAAO,EACP,cAAc,EACd,gBAAgB,GACjB,MAAM,WAAW,CAAC;AACnB,YAAY,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC"}
@@ -0,0 +1 @@
1
+ export { getValueAtPath, hasValueAtPath, pathKey, setValueAtPath, unsetValueAtPath, } from "./path.js";
@@ -0,0 +1,25 @@
1
+ /** Path to a value inside a schema tree form. */
2
+ export type SchemaPath = readonly (string | number)[];
3
+ /** Reads a nested value by schema path. */
4
+ export declare function getValueAtPath(source: unknown, path: SchemaPath): unknown;
5
+ /**
6
+ * Reports whether `path` resolves to an own, explicitly present key distinct from `getValueAtPath` returning `undefined`, which is also what a truly absent path returns. Needed to tell "the field was cleared to undefined" apart from "the field was never touched."
7
+ */
8
+ export declare function hasValueAtPath(source: unknown, path: SchemaPath): boolean;
9
+ /** Converts a schema path into the dot-separated key used by form state. */
10
+ export declare function pathKey(path: SchemaPath): string;
11
+ /**
12
+ * Immutably removes the key at `path`, cloning only the containers along the
13
+ * way (mirroring `setValueAtPath`'s own permissive style for a missing
14
+ * intermediate container, rather than special-casing it). A no-op for an
15
+ * empty path, a non-object source, or a terminal path segment landing on an
16
+ * array schema-tree field paths always terminate in a field name (a
17
+ * string key on an object), never an array index, since repeater rows are
18
+ * objects with named fields.
19
+ */
20
+ export declare function unsetValueAtPath(source: unknown, path: SchemaPath): unknown;
21
+ /**
22
+ * Immutably sets `value` at `path`, cloning only the containers along the way.
23
+ */
24
+ export declare function setValueAtPath(source: unknown, path: SchemaPath, value: unknown): unknown;
25
+ //# sourceMappingURL=path.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"path.d.ts","sourceRoot":"","sources":["../../src/layout/path.ts"],"names":[],"mappings":"AAAA,iDAAiD;AACjD,MAAM,MAAM,UAAU,GAAG,SAAS,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,CAAC;AAEtD,2CAA2C;AAC3C,wBAAgB,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,UAAU,GAAG,OAAO,CAQzE;AAED;;GAEG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,UAAU,GAAG,OAAO,CAezE;AAED,4EAA4E;AAC5E,wBAAgB,OAAO,CAAC,IAAI,EAAE,UAAU,GAAG,MAAM,CAEhD;AAED;;;;;;;;GAQG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,UAAU,GAAG,OAAO,CA6B3E;AAED;;GAEG;AACH,wBAAgB,cAAc,CAC5B,MAAM,EAAE,OAAO,EACf,IAAI,EAAE,UAAU,EAChB,KAAK,EAAE,OAAO,GACb,OAAO,CAsBT"}
@@ -0,0 +1,74 @@
1
+ /** Reads a nested value by schema path. */
2
+ export function getValueAtPath(source, path) {
3
+ return path.reduce((value, key) => {
4
+ if (value === null || value === undefined) {
5
+ return undefined;
6
+ }
7
+ return value[key];
8
+ }, source);
9
+ }
10
+ /**
11
+ * Reports whether `path` resolves to an own, explicitly present key distinct from `getValueAtPath` returning `undefined`, which is also what a truly absent path returns. Needed to tell "the field was cleared to undefined" apart from "the field was never touched."
12
+ */
13
+ export function hasValueAtPath(source, path) {
14
+ if (path.length === 0) {
15
+ return true;
16
+ }
17
+ const parent = getValueAtPath(source, path.slice(0, -1));
18
+ const key = path[path.length - 1];
19
+ if (parent === null || typeof parent !== "object") {
20
+ return false;
21
+ }
22
+ return Array.isArray(parent)
23
+ ? typeof key === "number" && key >= 0 && key < parent.length
24
+ : Object.hasOwn(parent, key);
25
+ }
26
+ /** Converts a schema path into the dot-separated key used by form state. */
27
+ export function pathKey(path) {
28
+ return path.join(".");
29
+ }
30
+ /**
31
+ * Immutably removes the key at `path`, cloning only the containers along the
32
+ * way (mirroring `setValueAtPath`'s own permissive style for a missing
33
+ * intermediate container, rather than special-casing it). A no-op for an
34
+ * empty path, a non-object source, or a terminal path segment landing on an
35
+ * array schema-tree field paths always terminate in a field name (a
36
+ * string key on an object), never an array index, since repeater rows are
37
+ * objects with named fields.
38
+ */
39
+ export function unsetValueAtPath(source, path) {
40
+ if (path.length === 0 || typeof source !== "object" || source === null) {
41
+ return source;
42
+ }
43
+ const [key, ...rest] = path;
44
+ if (rest.length === 0) {
45
+ if (Array.isArray(source)) {
46
+ return source;
47
+ }
48
+ const { [key]: _removed, ...remaining } = source;
49
+ return remaining;
50
+ }
51
+ const container = Array.isArray(source)
52
+ ? [...source]
53
+ : { ...source };
54
+ container[key] = unsetValueAtPath(container[key], rest);
55
+ return container;
56
+ }
57
+ /**
58
+ * Immutably sets `value` at `path`, cloning only the containers along the way.
59
+ */
60
+ export function setValueAtPath(source, path, value) {
61
+ if (path.length === 0) {
62
+ return value;
63
+ }
64
+ const [key, ...rest] = path;
65
+ const container = typeof key === "number"
66
+ ? Array.isArray(source)
67
+ ? [...source]
68
+ : []
69
+ : typeof source === "object" && source !== null
70
+ ? { ...source }
71
+ : {};
72
+ container[key] = setValueAtPath(container[key], rest, value);
73
+ return container;
74
+ }
@@ -0,0 +1,5 @@
1
+ export { resourceQueryKeys } from "./query-keys.js";
2
+ export type { ResourceQueryKeys } from "./query-keys.js";
3
+ export { patchCachedListRecord, recordId, removeCachedListRecord, restoreDeletedRecord, restoreResourceQueries, snapshotResourceQueries, } from "./optimistic.js";
4
+ export type { ResourceQuerySnapshot } from "./optimistic.js";
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/query/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACpD,YAAY,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACzD,OAAO,EACL,qBAAqB,EACrB,QAAQ,EACR,sBAAsB,EACtB,oBAAoB,EACpB,sBAAsB,EACtB,uBAAuB,GACxB,MAAM,iBAAiB,CAAC;AACzB,YAAY,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAC"}
@@ -0,0 +1,2 @@
1
+ export { resourceQueryKeys } from "./query-keys.js";
2
+ export { patchCachedListRecord, recordId, removeCachedListRecord, restoreDeletedRecord, restoreResourceQueries, snapshotResourceQueries, } from "./optimistic.js";
@@ -0,0 +1,24 @@
1
+ import type { QueryClient, QueryKey } from "@tanstack/query-core";
2
+ import type { ResourceQueryKeys } from "./query-keys.js";
3
+ export type ResourceQuerySnapshot = Array<[QueryKey, unknown]>;
4
+ /**
5
+ * Snapshots every cached query under a resource's key prefix, for rollback on error.
6
+ */
7
+ export declare function snapshotResourceQueries(queryClient: QueryClient, keys: ResourceQueryKeys): ResourceQuerySnapshot;
8
+ /**
9
+ * Restores a snapshot taken by `snapshotResourceQueries`, recreating any entry that was removed.
10
+ */
11
+ export declare function restoreResourceQueries(queryClient: QueryClient, snapshot: ResourceQuerySnapshot): void;
12
+ export declare function recordId(record: unknown): string | undefined;
13
+ /**
14
+ * Restores only the failed optimistic delete to avoid reviving records
15
+ * removed by concurrent mutations.
16
+ */
17
+ export declare function restoreDeletedRecord<TRecord>(queryClient: QueryClient, snapshot: ResourceQuerySnapshot, id: string): void;
18
+ /**
19
+ * Optimistically patches a record by id across every cached list page. A record whose `id` doesn't match (or that has no string/numeric `id` at all) is left untouched the eventual `invalidateQueries` on success still resolves any list this can't safely predict.
20
+ */
21
+ export declare function patchCachedListRecord<TRecord>(queryClient: QueryClient, keys: ResourceQueryKeys, id: string, patch: (record: TRecord) => TRecord): void;
22
+ /** Optimistically removes a record by id from every cached list page. */
23
+ export declare function removeCachedListRecord<TRecord>(queryClient: QueryClient, keys: ResourceQueryKeys, id: string): void;
24
+ //# sourceMappingURL=optimistic.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"optimistic.d.ts","sourceRoot":"","sources":["../../src/query/optimistic.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAElE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAEzD,MAAM,MAAM,qBAAqB,GAAG,KAAK,CAAC,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC,CAAC;AAE/D;;GAEG;AACH,wBAAgB,uBAAuB,CACrC,WAAW,EAAE,WAAW,EACxB,IAAI,EAAE,iBAAiB,GACtB,qBAAqB,CAEvB;AAED;;GAEG;AACH,wBAAgB,sBAAsB,CACpC,WAAW,EAAE,WAAW,EACxB,QAAQ,EAAE,qBAAqB,GAC9B,IAAI,CAIN;AAgBD,wBAAgB,QAAQ,CAAC,MAAM,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAY5D;AAKD;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAC1C,WAAW,EAAE,WAAW,EACxB,QAAQ,EAAE,qBAAqB,EAC/B,EAAE,EAAE,MAAM,GACT,IAAI,CA8BN;AAED;;GAEG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,EAC3C,WAAW,EAAE,WAAW,EACxB,IAAI,EAAE,iBAAiB,EACvB,EAAE,EAAE,MAAM,EACV,KAAK,EAAE,CAAC,MAAM,EAAE,OAAO,KAAK,OAAO,GAClC,IAAI,CAWN;AAED,yEAAyE;AACzE,wBAAgB,sBAAsB,CAAC,OAAO,EAC5C,WAAW,EAAE,WAAW,EACxB,IAAI,EAAE,iBAAiB,EACvB,EAAE,EAAE,MAAM,GACT,IAAI,CAeN"}
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Snapshots every cached query under a resource's key prefix, for rollback on error.
3
+ */
4
+ export function snapshotResourceQueries(queryClient, keys) {
5
+ return queryClient.getQueriesData({ queryKey: keys.all });
6
+ }
7
+ /**
8
+ * Restores a snapshot taken by `snapshotResourceQueries`, recreating any entry that was removed.
9
+ */
10
+ export function restoreResourceQueries(queryClient, snapshot) {
11
+ for (const [queryKey, data] of snapshot) {
12
+ queryClient.setQueryData(queryKey, data);
13
+ }
14
+ }
15
+ function isListResponse(value) {
16
+ return (typeof value === "object" &&
17
+ value !== null &&
18
+ "records" in value &&
19
+ "total" in value &&
20
+ Array.isArray(value.records) &&
21
+ typeof value.total === "number");
22
+ }
23
+ // Normalize adapter IDs to strings so numeric IDs match the resource contract.
24
+ export function recordId(record) {
25
+ const value = record?.id;
26
+ if (typeof value === "string") {
27
+ return value;
28
+ }
29
+ if (typeof value === "number") {
30
+ return String(value);
31
+ }
32
+ return undefined;
33
+ }
34
+ const isListQuery = (query) => query.queryKey[2] === "list";
35
+ /**
36
+ * Restores only the failed optimistic delete to avoid reviving records
37
+ * removed by concurrent mutations.
38
+ */
39
+ export function restoreDeletedRecord(queryClient, snapshot, id) {
40
+ for (const [queryKey, previous] of snapshot) {
41
+ if (isListQuery({ queryKey }) && isListResponse(previous)) {
42
+ const deletedRecord = previous.records.find((record) => recordId(record) === id);
43
+ if (!deletedRecord)
44
+ continue;
45
+ queryClient.setQueryData(queryKey, (current) => {
46
+ if (!current ||
47
+ current.records.some((record) => recordId(record) === id)) {
48
+ return current;
49
+ }
50
+ return {
51
+ ...current,
52
+ records: [...current.records, deletedRecord],
53
+ total: current.total + 1,
54
+ };
55
+ });
56
+ continue;
57
+ }
58
+ if (queryKey[2] === "find" && queryKey[3] === id) {
59
+ queryClient.setQueryData(queryKey, previous);
60
+ }
61
+ }
62
+ }
63
+ /**
64
+ * Optimistically patches a record by id across every cached list page. A record whose `id` doesn't match (or that has no string/numeric `id` at all) is left untouched the eventual `invalidateQueries` on success still resolves any list this can't safely predict.
65
+ */
66
+ export function patchCachedListRecord(queryClient, keys, id, patch) {
67
+ queryClient.setQueriesData({ queryKey: keys.all, predicate: isListQuery }, (data) => data && {
68
+ ...data,
69
+ records: data.records.map((record) => recordId(record) === id ? patch(record) : record),
70
+ });
71
+ }
72
+ /** Optimistically removes a record by id from every cached list page. */
73
+ export function removeCachedListRecord(queryClient, keys, id) {
74
+ queryClient.setQueriesData({ queryKey: keys.all, predicate: isListQuery }, (data) => {
75
+ if (!data) {
76
+ return data;
77
+ }
78
+ const records = data.records.filter((record) => recordId(record) !== id);
79
+ return records.length === data.records.length
80
+ ? data
81
+ : { ...data, records, total: data.total - 1 };
82
+ });
83
+ }
@@ -0,0 +1,12 @@
1
+ import type { ListParams } from "@verikit/client";
2
+ export interface ResourceQueryKeys {
3
+ all: readonly [string, string];
4
+ list: (params?: ListParams) => readonly [string, string, "list", ListParams];
5
+ find: (id: string) => readonly [string, string, "find", string];
6
+ relationship: (relationshipName: string, params?: ListParams) => readonly [string, string, "relationship", string, ListParams];
7
+ }
8
+ /**
9
+ * Builds the query keys the resource hooks use, so query hooks and mutation hooks' invalidation calls always agree on the same shape. Exported so consumers can invalidate/read the same cache entries themselves (e.g. reacting to a websocket event) without guessing at the internal shape.
10
+ */
11
+ export declare function resourceQueryKeys(name: string): ResourceQueryKeys;
12
+ //# sourceMappingURL=query-keys.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query-keys.d.ts","sourceRoot":"","sources":["../../src/query/query-keys.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAElD,MAAM,WAAW,iBAAiB;IAChC,GAAG,EAAE,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC/B,IAAI,EAAE,CAAC,MAAM,CAAC,EAAE,UAAU,KAAK,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,CAAC,CAAC;IAC7E,IAAI,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;IAChE,YAAY,EAAE,CACZ,gBAAgB,EAAE,MAAM,EACxB,MAAM,CAAC,EAAE,UAAU,KAChB,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,EAAE,UAAU,CAAC,CAAC;CACpE;AAED;;GAEG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,iBAAiB,CASjE"}
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Builds the query keys the resource hooks use, so query hooks and mutation hooks' invalidation calls always agree on the same shape. Exported so consumers can invalidate/read the same cache entries themselves (e.g. reacting to a websocket event) without guessing at the internal shape.
3
+ */
4
+ export function resourceQueryKeys(name) {
5
+ return {
6
+ all: ["verikit", name],
7
+ list: (params = {}) => ["verikit", name, "list", params],
8
+ find: (id) => ["verikit", name, "find", id],
9
+ relationship: (relationshipName, params = {}) => ["verikit", name, "relationship", relationshipName, params],
10
+ };
11
+ }
package/package.json ADDED
@@ -0,0 +1,60 @@
1
+ {
2
+ "name": "@verikit/ui-core",
3
+ "version": "0.23.1",
4
+ "description": "Framework-neutral form, layout, and query logic shared by Verikit UI bindings.",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "keywords": [
8
+ "typescript",
9
+ "resource",
10
+ "schema",
11
+ "resource-model",
12
+ "metadata",
13
+ "builder",
14
+ "validation",
15
+ "framework"
16
+ ],
17
+ "author": "Chidi E <hi@ceeso.dev>",
18
+ "license": "MIT",
19
+ "engines": {
20
+ "node": ">=24"
21
+ },
22
+ "types": "./dist/index.d.ts",
23
+ "exports": {
24
+ ".": {
25
+ "types": "./dist/index.d.ts",
26
+ "default": "./dist/index.js"
27
+ },
28
+ "./form/*": {
29
+ "types": "./dist/form/*.d.ts",
30
+ "default": "./dist/form/*.js"
31
+ },
32
+ "./layout/*": {
33
+ "types": "./dist/layout/*.d.ts",
34
+ "default": "./dist/layout/*.js"
35
+ },
36
+ "./query/*": {
37
+ "types": "./dist/query/*.d.ts",
38
+ "default": "./dist/query/*.js"
39
+ }
40
+ },
41
+ "files": [
42
+ "dist"
43
+ ],
44
+ "dependencies": {
45
+ "@tanstack/query-core": "^5.101.4",
46
+ "@verikit/client": "0.23.1",
47
+ "@verikit/core": "0.23.1",
48
+ "@verikit/runtime": "0.23.1"
49
+ },
50
+ "devDependencies": {
51
+ "@types/node": "^26.1.1",
52
+ "typescript": "^6.0.3"
53
+ },
54
+ "scripts": {
55
+ "clean": "rm -rf dist tsconfig.tsbuildinfo",
56
+ "build": "pnpm clean && tsc -b",
57
+ "test": "rm -rf .test-dist && tsc -p tsconfig.test.json && node --test $(find ./.test-dist/test -name '*.test.js' -type f | sort)",
58
+ "test:coverage": "rm -rf .test-dist coverage && tsc -p tsconfig.test.json && node --test --experimental-test-coverage --test-coverage-include='.test-dist/src/**/*.js' --test-coverage-lines=100 --test-coverage-branches=100 --test-coverage-functions=100 $(find ./.test-dist/test -name '*.test.js' -type f | sort)"
59
+ }
60
+ }