@punica/form-mcp 0.3.1 → 0.4.0-next.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 +8 -6
- package/bundled/form/define/Form.d.ts +41 -0
- package/bundled/form/define/index.d.ts +2 -0
- package/bundled/form/model/command/service.d.ts +7 -1
- package/bundled/form/model/constants/index.d.ts +4 -0
- package/bundled/form/model/form/index.d.ts +23 -0
- package/bundled/form/model/item/index.d.ts +28 -2
- package/bundled/form/package.json +1 -1
- package/bundled/form/utils/index.d.ts +1 -0
- package/bundled/form/utils/isEqual.d.ts +7 -0
- package/bundled/form-json/conditions.d.ts +8 -0
- package/bundled/form-json/definition/fromJsonSchema.d.ts +22 -0
- package/bundled/form-json/definition/index.d.ts +6 -0
- package/bundled/form-json/definition/limits.d.ts +31 -0
- package/bundled/form-json/definition/schema.d.ts +202 -0
- package/bundled/form-json/definition/types.d.ts +87 -0
- package/bundled/form-json/definition/validate.d.ts +15 -0
- package/bundled/form-json/fromSchema.d.ts +50 -0
- package/bundled/form-json/index.d.ts +4 -0
- package/bundled/form-json/package.json +1 -0
- package/bundled/form-json/rules.d.ts +19 -0
- package/bundled/form-kit/decorators.d.ts +4 -1
- package/bundled/form-kit/json/index.d.ts +33 -0
- package/bundled/form-kit/package.json +1 -1
- package/bundled/form-kit/react/index.d.ts +3 -1
- package/bundled/form-react/index.d.ts +2 -0
- package/bundled/form-react/package.json +1 -1
- package/bundled/form-react/useController.d.ts +15 -0
- package/bundled/form-react/useFormController.d.ts +2 -7
- package/bundled/form-react/useFormState.d.ts +7 -0
- package/bundled/form-service/index.d.ts +6 -0
- package/bundled/form-service/message.d.ts +2 -0
- package/bundled/form-service/package.json +1 -1
- package/bundled/form-service/readValues.d.ts +6 -0
- package/bundled/form-service/submit/index.d.ts +20 -0
- package/bundled/form-service/touch/index.d.ts +13 -0
- package/bundled/form-service/trigger/index.d.ts +3 -0
- package/bundled/form-service/validateItem.d.ts +25 -9
- package/package.json +6 -5
- package/src/create.mjs +78 -3
- package/src/guide.md +75 -4
- package/src/load.mjs +7 -2
- package/src/main.mjs +4 -2
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { JsonValue } from './definition';
|
|
2
|
+
/** What a rule knows about the item it checks. */
|
|
3
|
+
export type RuleContext = {
|
|
4
|
+
/** The `value` of the rule in the definition. */
|
|
5
|
+
value?: JsonValue;
|
|
6
|
+
/** The label of the item. */
|
|
7
|
+
label: string;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* A validation rule: returns the message for a value that breaks it and
|
|
11
|
+
* `undefined` for one that does not. It may ask a server.
|
|
12
|
+
*/
|
|
13
|
+
export type Rule = (value: unknown, context: RuleContext) => string | undefined | Promise<string | undefined>;
|
|
14
|
+
export declare const isEmpty: (value: unknown) => boolean;
|
|
15
|
+
/**
|
|
16
|
+
* The rules every form definition can use. Except for `required`, a rule is
|
|
17
|
+
* not asked about an empty value.
|
|
18
|
+
*/
|
|
19
|
+
export declare const builtInRules: Record<string, Rule>;
|
|
@@ -7,7 +7,10 @@ export type FormKitOptions = {
|
|
|
7
7
|
description?: string;
|
|
8
8
|
/** Columns the fields are laid out in, 1 by default. */
|
|
9
9
|
columns?: 1 | 2 | 3 | 4;
|
|
10
|
-
/**
|
|
10
|
+
/**
|
|
11
|
+
* Services in addition to GetValues, SetValue, Validate, Trigger, Reset,
|
|
12
|
+
* Touch and Submit.
|
|
13
|
+
*/
|
|
11
14
|
services?: Array<IService | (new () => IService)>;
|
|
12
15
|
/** Readers in addition to the kit's. */
|
|
13
16
|
readers?: Array<IReader<any, any>>;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { ReactNode } from 'react';
|
|
2
|
+
import { FromSchemaOptions, JsonFormValues } from '@punica/form-json';
|
|
3
|
+
import { type FormViewProps } from '../react';
|
|
4
|
+
/**
|
|
5
|
+
* The types a form definition may use with the kit, and the form item type
|
|
6
|
+
* of the kit each one stands for.
|
|
7
|
+
*/
|
|
8
|
+
export declare const KIT_JSON_TYPES: Record<string, string>;
|
|
9
|
+
export type JsonFormProps = Omit<FormViewProps<JsonFormValues>, 'controller'> & {
|
|
10
|
+
/**
|
|
11
|
+
* The form definition, read when the component mounts. It is checked
|
|
12
|
+
* before anything is rendered, so it may come from a language model.
|
|
13
|
+
* Give the component a `key` to show another definition.
|
|
14
|
+
*/
|
|
15
|
+
definition: unknown;
|
|
16
|
+
/** Rules, services and types in addition to the kit's. */
|
|
17
|
+
options?: FromSchemaOptions;
|
|
18
|
+
/** Shown while the form is being started. */
|
|
19
|
+
loading?: ReactNode;
|
|
20
|
+
/**
|
|
21
|
+
* Shown when the definition is not valid or the form could not be
|
|
22
|
+
* started; receives what was thrown, a `FormDefinitionError` for a
|
|
23
|
+
* definition that is not valid.
|
|
24
|
+
*/
|
|
25
|
+
failed?: (error: unknown) => ReactNode;
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* A complete form from a form definition: checks the definition, creates
|
|
29
|
+
* its controller, starts it and renders it with `@punica/components`.
|
|
30
|
+
*
|
|
31
|
+
* <JsonForm definition={definition} onSubmit={(values) => save(values)} />
|
|
32
|
+
*/
|
|
33
|
+
export declare function JsonForm({ definition, options, loading, failed, ...view }: JsonFormProps): ReactNode;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":"0.
|
|
1
|
+
{"version":"0.3.0-next.0"}
|
|
@@ -12,7 +12,8 @@ type ViewProps<E extends object> = {
|
|
|
12
12
|
onSubmit?: (values: E, controller: FormController<E, KitItem<E>>) => void | Promise<void>;
|
|
13
13
|
/**
|
|
14
14
|
* Called with what a validation, a control function or `onSubmit` threw.
|
|
15
|
-
* Without it the error is logged to the console.
|
|
15
|
+
* Without it the error is logged to the console. What a submit throws is
|
|
16
|
+
* also shown above the fields.
|
|
16
17
|
*/
|
|
17
18
|
onError?: (error: unknown) => void;
|
|
18
19
|
/** The text of the submit button, `Submit` by default. */
|
|
@@ -23,6 +24,7 @@ type ViewProps<E extends object> = {
|
|
|
23
24
|
components?: Record<string, FieldComponent>;
|
|
24
25
|
};
|
|
25
26
|
export type FormViewProps<E extends object> = ViewProps<E> & {
|
|
27
|
+
/** A started controller of a `@FormKit` class, which brings the services the view needs. */
|
|
26
28
|
controller: FormController<E, KitItem<E>>;
|
|
27
29
|
};
|
|
28
30
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":"0.
|
|
1
|
+
{"version":"0.2.0-next.0"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { FormController, FormItem } from '@punica/form';
|
|
2
|
+
export type FormControllerState<E extends object, F extends FormItem<E>> = {
|
|
3
|
+
/** The started controller; `undefined` while the form is being started. */
|
|
4
|
+
controller?: FormController<E, F>;
|
|
5
|
+
/** What was thrown while the form was created or started. */
|
|
6
|
+
error?: unknown;
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* Creates a controller when the component mounts and starts it. Use it for
|
|
10
|
+
* forms that are not made from an entity, such as a form described as data;
|
|
11
|
+
* for a form class there is `useFormController`.
|
|
12
|
+
* @param create - Returns the controller, not started; read when the
|
|
13
|
+
* component mounts. Give the component a `key` to create another form
|
|
14
|
+
*/
|
|
15
|
+
export declare const useController: <E extends object, F extends FormItem<E> = FormItem<E>>(create: () => FormController<E, F> | Promise<FormController<E, F>>) => FormControllerState<E, F>;
|
|
@@ -1,10 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
/** The started controller; `undefined` while the form is being started. */
|
|
4
|
-
controller?: FormController<E, F>;
|
|
5
|
-
/** What a reader, a starter or a service threw while the form was started. */
|
|
6
|
-
error?: unknown;
|
|
7
|
-
};
|
|
1
|
+
import { FormControllerOptions, FormItem } from '@punica/form';
|
|
2
|
+
import { FormControllerState } from './useController';
|
|
8
3
|
/**
|
|
9
4
|
* Creates the controller of a form when the component mounts and starts it.
|
|
10
5
|
* @param createEntity - Returns the entity of the form, for example `() => new UserForm()`
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { FormController, FormItem, FormState } from '@punica/form';
|
|
2
|
+
/**
|
|
3
|
+
* The state of a form as a whole: dirty, touched, valid, validating, submitting, its
|
|
4
|
+
* submit count and its errors. Unlike `useForm`, the component only renders
|
|
5
|
+
* again when this state changes, not after every change of an item.
|
|
6
|
+
*/
|
|
7
|
+
export declare const useFormState: <E extends object, F extends FormItem<E>>(controller: FormController<E, F>) => FormState;
|
|
@@ -5,6 +5,8 @@ import type { GetValues } from './getValues';
|
|
|
5
5
|
import type { Reset } from './reset';
|
|
6
6
|
import type { ResetItem } from './resetItem';
|
|
7
7
|
import type { SetValue } from './setValue';
|
|
8
|
+
import type { Submit } from './submit';
|
|
9
|
+
import type { Touch } from './touch';
|
|
8
10
|
import type { Trigger } from './trigger';
|
|
9
11
|
import type { Validate } from './validate';
|
|
10
12
|
export * from './clearError';
|
|
@@ -14,6 +16,8 @@ export * from './reset';
|
|
|
14
16
|
export * from './resetItem';
|
|
15
17
|
export * from './setValue';
|
|
16
18
|
export * from './store';
|
|
19
|
+
export * from './submit';
|
|
20
|
+
export * from './touch';
|
|
17
21
|
export * from './trigger';
|
|
18
22
|
export * from './validate';
|
|
19
23
|
declare module '@punica/form' {
|
|
@@ -24,6 +28,8 @@ declare module '@punica/form' {
|
|
|
24
28
|
reset: Reset<E, F>;
|
|
25
29
|
resetItem: ResetItem<E, F>;
|
|
26
30
|
setValue: SetValue<E, F>;
|
|
31
|
+
submit: Submit<E, F>;
|
|
32
|
+
touch: Touch<E, F>;
|
|
27
33
|
trigger: Trigger<E, F>;
|
|
28
34
|
validate: Validate<E, F>;
|
|
29
35
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":"2.
|
|
1
|
+
{"version":"2.2.0-next.0"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { CommandService, FormItem } from '@punica/form';
|
|
2
|
+
/**
|
|
3
|
+
* A copy of the entity the form was created from, holding the current
|
|
4
|
+
* values. The entity itself is never changed.
|
|
5
|
+
*/
|
|
6
|
+
export declare const readValues: <E, F extends FormItem<E>>(command: CommandService<E, F>) => E;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { CommandService, FormItem, IServiceControl, IServiceInitialize } from '@punica/form';
|
|
2
|
+
/**
|
|
3
|
+
* Submits the form: validates it and gives its values to a handler.
|
|
4
|
+
*/
|
|
5
|
+
export declare class Submit<E, F extends FormItem<E> = FormItem<E>> implements IServiceInitialize<E, F>, IServiceControl {
|
|
6
|
+
#private;
|
|
7
|
+
get name(): string;
|
|
8
|
+
initialize(command: CommandService<E, F>): void;
|
|
9
|
+
/**
|
|
10
|
+
* Validates every item and, when the form is valid, calls the handler with
|
|
11
|
+
* its values and fires SUBMIT. While it runs the state of the form is
|
|
12
|
+
* `submitting`; a submit that is started meanwhile is ignored.
|
|
13
|
+
*
|
|
14
|
+
* What the handler or a validation throws does not reject: the message of
|
|
15
|
+
* the error, or a general one when it has none, becomes an error of the
|
|
16
|
+
* form (`state.errors`) and SUBMIT_ERROR is fired.
|
|
17
|
+
* @returns Whether the form was valid and the handler finished
|
|
18
|
+
*/
|
|
19
|
+
run(handler?: (values: E) => void | Promise<void>): Promise<boolean>;
|
|
20
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { CommandService, FormItem, IServiceControl, IServiceInitialize } from '@punica/form';
|
|
2
|
+
/**
|
|
3
|
+
* Marks an item as touched: the user has left its field.
|
|
4
|
+
*/
|
|
5
|
+
export declare class Touch<E, F extends FormItem<E> = FormItem<E>> implements IServiceInitialize<E, F>, IServiceControl {
|
|
6
|
+
#private;
|
|
7
|
+
get name(): string;
|
|
8
|
+
initialize(command: CommandService<E, F>): void;
|
|
9
|
+
/**
|
|
10
|
+
* @throws When the form has no item for the property
|
|
11
|
+
*/
|
|
12
|
+
run(property: keyof E): Promise<void>;
|
|
13
|
+
}
|
|
@@ -7,6 +7,9 @@ export declare class Trigger<E, F extends FormItem<E> = FormItem<E>> implements
|
|
|
7
7
|
get name(): string;
|
|
8
8
|
initialize(command: CommandService<E, F>): void;
|
|
9
9
|
/**
|
|
10
|
+
* Waits for `validateDebounce` of the item first, when it has one; the
|
|
11
|
+
* validation is skipped when the item is triggered again, validated,
|
|
12
|
+
* changed or reset meanwhile.
|
|
10
13
|
* @throws When the form has no item for the property
|
|
11
14
|
*/
|
|
12
15
|
run(property: keyof E): Promise<void>;
|
|
@@ -1,16 +1,32 @@
|
|
|
1
|
-
import { CommandService,
|
|
1
|
+
import { CommandService, FormItem } from '@punica/form';
|
|
2
2
|
/**
|
|
3
|
-
*
|
|
4
|
-
*
|
|
3
|
+
* Cancels the validations of a form that are running or waiting for their
|
|
4
|
+
* delay: of one property, or of every property. Their `signal` is aborted
|
|
5
|
+
* and their results are not written.
|
|
5
6
|
*/
|
|
6
7
|
export declare const dropValidations: <E, F extends FormItem<E>>(command: CommandService<E, F>, property?: keyof E) => void;
|
|
7
8
|
/**
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
|
|
9
|
+
* Waits for the delay of a validation (`validateDebounce` of the item).
|
|
10
|
+
* @returns Whether to validate: `false` when the property was validated,
|
|
11
|
+
* changed again or reset before the delay was over
|
|
12
|
+
*/
|
|
13
|
+
export declare const delayValidation: <E, F extends FormItem<E>>(command: CommandService<E, F>, property: keyof E, milliseconds: number) => Promise<boolean>;
|
|
14
|
+
/**
|
|
15
|
+
* Validates items one after the other, each as it is when its turn comes,
|
|
16
|
+
* and writes the results onto the items as they are then: only the error
|
|
17
|
+
* state is what a validation knows.
|
|
18
|
+
*
|
|
19
|
+
* A validation is cancelled when its item is validated again, changed or
|
|
20
|
+
* reset. The validation that replaced it counts then. When a verdict on the
|
|
21
|
+
* items is asked for, an item that changed is validated again with its new
|
|
22
|
+
* value; otherwise it is left alone. A result is never written onto a value
|
|
23
|
+
* it was not made for. Items that take a while are `validating`.
|
|
24
|
+
*
|
|
12
25
|
* Items without a validation function, hidden items and disabled items are
|
|
13
26
|
* not validated.
|
|
14
|
-
* @returns
|
|
27
|
+
* @returns Whether every validated item is valid. `false` as well when the
|
|
28
|
+
* form was reset meanwhile
|
|
15
29
|
*/
|
|
16
|
-
export declare const validateItems: <E, F extends FormItem<E>>(command: CommandService<E, F>, items: F[]
|
|
30
|
+
export declare const validateItems: <E, F extends FormItem<E>>(command: CommandService<E, F>, items: F[], { verdict }?: {
|
|
31
|
+
verdict?: boolean;
|
|
32
|
+
}) => Promise<boolean>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@punica/form-mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0-next.0",
|
|
4
4
|
"description": "MCP server for Punica Form: look up the exact API of its packages, read the rules and check code that uses them.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"mcp",
|
|
@@ -36,13 +36,14 @@
|
|
|
36
36
|
},
|
|
37
37
|
"dependencies": {
|
|
38
38
|
"@modelcontextprotocol/sdk": "^1.32.2",
|
|
39
|
+
"@punica/form-json": "^0.1.0-next.0",
|
|
39
40
|
"zod": "^4.6.7"
|
|
40
41
|
},
|
|
41
42
|
"devDependencies": {
|
|
42
|
-
"@punica/form": "^2.
|
|
43
|
-
"@punica/form-service": "^2.
|
|
44
|
-
"@punica/form-react": "^0.
|
|
45
|
-
"@punica/form-kit": "^0.
|
|
43
|
+
"@punica/form": "^2.2.0-next.0",
|
|
44
|
+
"@punica/form-service": "^2.2.0-next.0",
|
|
45
|
+
"@punica/form-react": "^0.2.0-next.0",
|
|
46
|
+
"@punica/form-kit": "^0.3.0-next.0"
|
|
46
47
|
},
|
|
47
48
|
"scripts": {
|
|
48
49
|
"build": "node build.mjs",
|
package/src/create.mjs
CHANGED
|
@@ -2,12 +2,22 @@
|
|
|
2
2
|
// its rules and the code validator. Transport-free, so tests connect it to
|
|
3
3
|
// an in-memory client.
|
|
4
4
|
import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
5
|
+
import { fromJsonSchema, formDefinitionSchema, validateDefinition } from '@punica/form-json/definition';
|
|
5
6
|
import { z } from 'zod';
|
|
7
|
+
import { readFileSync } from 'node:fs';
|
|
6
8
|
import { createKnowledge } from './knowledge.mjs';
|
|
7
9
|
import { createValidator } from './validate.mjs';
|
|
8
10
|
|
|
11
|
+
const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
12
|
+
|
|
9
13
|
const text = (value) => ({ content: [{ type: 'text', text: value }] });
|
|
10
14
|
|
|
15
|
+
/** The types a form definition may use when the form kit renders it. */
|
|
16
|
+
const KIT_TYPES = ['text', 'textarea', 'number', 'select', 'checkbox', 'switch'];
|
|
17
|
+
|
|
18
|
+
/** A tool argument that is JSON: given as an object, or as its text. */
|
|
19
|
+
const parse = (value) => (typeof value === 'string' ? JSON.parse(value) : value);
|
|
20
|
+
|
|
11
21
|
/**
|
|
12
22
|
* @param {{ packages: Array<Parameters<typeof createKnowledge>[0][number] & { installed?: boolean }>, guide: string }} options
|
|
13
23
|
* `installed` says whether the declarations come from the project or from
|
|
@@ -29,9 +39,9 @@ export function createPunicaFormServer({ packages, guide }) {
|
|
|
29
39
|
: '';
|
|
30
40
|
|
|
31
41
|
const server = new McpServer(
|
|
32
|
-
{ name: 'punica-form', version
|
|
42
|
+
{ name: 'punica-form', version },
|
|
33
43
|
{
|
|
34
|
-
instructions: `${legacyNote}${versions}. Punica Form is a headless form engine and is rarely in training data: never write an import, a service name or a method from memory. Read get_guide first, look names up with search_api and get_api, and check the code with validate_code before handing it over.`
|
|
44
|
+
instructions: `${legacyNote}${versions}. Punica Form is a headless form engine and is rarely in training data: never write an import, a service name or a method from memory. Read get_guide first, look names up with search_api and get_api, and check the code with validate_code before handing it over. To produce a form at run time as data instead of code, read get_form_schema and check the definition with validate_form.`
|
|
35
45
|
}
|
|
36
46
|
);
|
|
37
47
|
|
|
@@ -52,7 +62,7 @@ export function createPunicaFormServer({ packages, guide }) {
|
|
|
52
62
|
{
|
|
53
63
|
title: 'Find Punica Form exports',
|
|
54
64
|
description:
|
|
55
|
-
'Finds exports of the Punica Form packages (@punica/form, @punica/form-service, @punica/form-react, @punica/form-kit) by name or by words in their documentation ("validate", "reader", "field"). Without a query: every export.',
|
|
65
|
+
'Finds exports of the Punica Form packages (@punica/form, @punica/form-service, @punica/form-react, @punica/form-kit, @punica/form-json) by name or by words in their documentation ("validate", "reader", "field"). Without a query: every export.',
|
|
56
66
|
inputSchema: { query: z.string().optional().describe('Words to look for') },
|
|
57
67
|
annotations: { readOnlyHint: true }
|
|
58
68
|
},
|
|
@@ -108,6 +118,71 @@ export function createPunicaFormServer({ packages, guide }) {
|
|
|
108
118
|
}
|
|
109
119
|
);
|
|
110
120
|
|
|
121
|
+
server.registerTool(
|
|
122
|
+
'get_form_schema',
|
|
123
|
+
{
|
|
124
|
+
title: 'The format of a form described as data',
|
|
125
|
+
description:
|
|
126
|
+
'The JSON Schema of a Punica Form definition (@punica/form-json): a form as JSON that an application renders at run time, without code. Read it before writing a form definition, and use it as the schema of structured output.',
|
|
127
|
+
inputSchema: {},
|
|
128
|
+
annotations: { readOnlyHint: true }
|
|
129
|
+
},
|
|
130
|
+
async () =>
|
|
131
|
+
text(
|
|
132
|
+
[
|
|
133
|
+
`Types the form kit renders: ${KIT_TYPES.join(', ')}. An application may have its own.`,
|
|
134
|
+
'Rules: required, email, integer, min, max, minLength, maxLength, pattern; `value` holds the limit. An application may have more.',
|
|
135
|
+
'Conditions (visibleWhen, disabledWhen) compare the value of another item: { property, equals | notEquals | in }, combined with { all: [...] } and { any: [...] }.',
|
|
136
|
+
'A definition holds no code: no functions, no expressions, no HTML. Check it with validate_form.',
|
|
137
|
+
'',
|
|
138
|
+
JSON.stringify(formDefinitionSchema, null, 2)
|
|
139
|
+
].join('\n')
|
|
140
|
+
)
|
|
141
|
+
);
|
|
142
|
+
|
|
143
|
+
server.registerTool(
|
|
144
|
+
'validate_form',
|
|
145
|
+
{
|
|
146
|
+
title: 'Check a form definition',
|
|
147
|
+
description:
|
|
148
|
+
'Checks a form definition (the JSON of @punica/form-json) before it is given to an application: its shape, unknown types and rules, conditions that point to items that do not exist, duplicate properties and anything that is not data. Returns each problem with its path. Give `json_schema` instead to turn a flat JSON Schema into a form definition.',
|
|
149
|
+
inputSchema: {
|
|
150
|
+
definition: z.unknown().optional().describe('The form definition, as an object or as JSON text'),
|
|
151
|
+
json_schema: z.unknown().optional().describe('A JSON Schema to convert into a form definition instead'),
|
|
152
|
+
types: z.array(z.string()).optional().describe('The types the application renders; the types of the form kit by default'),
|
|
153
|
+
rules: z.array(z.string()).optional().describe('Names of rules the application has besides the built-in ones')
|
|
154
|
+
},
|
|
155
|
+
annotations: { readOnlyHint: true }
|
|
156
|
+
},
|
|
157
|
+
async ({ definition, json_schema: schema, types = KIT_TYPES, rules }) => {
|
|
158
|
+
let converted = '';
|
|
159
|
+
|
|
160
|
+
try {
|
|
161
|
+
if (schema !== undefined) {
|
|
162
|
+
definition = fromJsonSchema(parse(schema));
|
|
163
|
+
converted = `\n\n${JSON.stringify(definition, null, 2)}`;
|
|
164
|
+
} else {
|
|
165
|
+
definition = parse(definition);
|
|
166
|
+
}
|
|
167
|
+
} catch (error) {
|
|
168
|
+
return text(`Not usable: ${error.message}`);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const problems = validateDefinition(definition, { types, rules });
|
|
172
|
+
|
|
173
|
+
if (!problems.length) {
|
|
174
|
+
return text(`No problems: the form definition is valid.${converted}`);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
return text(
|
|
178
|
+
[
|
|
179
|
+
`${problems.length} problem${problems.length === 1 ? '' : 's'}:`,
|
|
180
|
+
...problems.map(({ path, message }) => `${path || 'definition'} ${message}`)
|
|
181
|
+
].join('\n') + converted
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
);
|
|
185
|
+
|
|
111
186
|
server.registerResource(
|
|
112
187
|
'guide',
|
|
113
188
|
'punica-form://guide',
|
package/src/guide.md
CHANGED
|
@@ -11,6 +11,7 @@ Punica Form is a headless form engine. `@punica/form` holds the engine,
|
|
|
11
11
|
`getFormProperty` and `getFormItemProperties`, the form item register,
|
|
12
12
|
`deepCopy`, the DevTools switches and the types. Use `search_api` for the
|
|
13
13
|
exact list.
|
|
14
|
+
- `@punica/form-json`: forms as data; see "Forms as data" below.
|
|
14
15
|
- `@punica/form-service`: `Validate`, `GetValues`, `SetValue`, `Reset`,
|
|
15
16
|
`ResetItem`, `Trigger`, `ClearError`, `ClearErrors`, `Store`.
|
|
16
17
|
- NOT provided: `@Title`, `@Description`, `@Layout`, `@FormItemInputText` or
|
|
@@ -21,6 +22,30 @@ Punica Form is a headless form engine. `@punica/form` holds the engine,
|
|
|
21
22
|
- Decorators work with both the legacy implementation of TypeScript
|
|
22
23
|
(`"experimentalDecorators": true`) and the standard one. There is no
|
|
23
24
|
`reflect-metadata`: never call `Reflect.getMetadata`.
|
|
25
|
+
- Before writing a decorated class, check that the build compiles decorator
|
|
26
|
+
syntax: `"experimentalDecorators": true` in `tsconfig.json` is enough for
|
|
27
|
+
Vite and esbuild. When it does not and you should not change it, define the
|
|
28
|
+
form with `defineForm` (since 2.2), which needs no decorator syntax. Every
|
|
29
|
+
decorator (`Services`, the kit's `TextField`, your own) is then a function
|
|
30
|
+
call:
|
|
31
|
+
|
|
32
|
+
```ts
|
|
33
|
+
import { defineForm, field, Services } from "@punica/form";
|
|
34
|
+
|
|
35
|
+
const UserForm = defineForm(
|
|
36
|
+
{
|
|
37
|
+
name: field("", Text({ label: "Name" })),
|
|
38
|
+
age: field<number | undefined>(undefined, NumberInput({ label: "Age" })),
|
|
39
|
+
},
|
|
40
|
+
Services([GetValues, SetValue]) // or FormKit({ title: "User" })
|
|
41
|
+
);
|
|
42
|
+
type User = InstanceType<typeof UserForm>;
|
|
43
|
+
|
|
44
|
+
const controller = await FormController.fromEntity(new UserForm({ name: "Jane" }));
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
The result is a form class like a decorated one; do not mix both styles in
|
|
48
|
+
one class. `fromEntity` warns when a class ends up without form items.
|
|
24
49
|
|
|
25
50
|
## The ready-made form system
|
|
26
51
|
|
|
@@ -30,9 +55,33 @@ Punica Form is a headless form engine. `@punica/form` holds the engine,
|
|
|
30
55
|
`SwitchField` with the rules `required`, `minLength`, `maxLength`, `pattern`,
|
|
31
56
|
`min` and `max`, and from `@punica/form-kit/react` the component
|
|
32
57
|
`<KitForm entity={() => new UserForm()} onSubmit={…} />`, which renders the
|
|
33
|
-
form with `@punica/components
|
|
58
|
+
form with `@punica/components`, shows what `onSubmit` throws above the
|
|
59
|
+
fields and reports it to `onError`. Use it when the project has it installed;
|
|
34
60
|
otherwise build the form system as described below.
|
|
35
61
|
|
|
62
|
+
## Forms as data, written at run time
|
|
63
|
+
|
|
64
|
+
Everything above is for code. When the form itself has to be produced at run
|
|
65
|
+
time (an agent asking the user for information, a form sent by a server),
|
|
66
|
+
write a form definition instead: JSON, no code. `@punica/form-json` checks
|
|
67
|
+
and runs it.
|
|
68
|
+
|
|
69
|
+
- Read `get_form_schema` for the format and check every definition with
|
|
70
|
+
`validate_form` before handing it over.
|
|
71
|
+
- Render it with `<JsonForm definition={definition} onSubmit={…} />` from
|
|
72
|
+
`@punica/form-kit/json`, or create the controller with
|
|
73
|
+
`fromSchema(definition, { types, rules })` from `@punica/form-json`. Both
|
|
74
|
+
refuse a definition that is not valid with a `FormDefinitionError` whose
|
|
75
|
+
`problems` have a `path` and a `message`.
|
|
76
|
+
- Types with the kit: `text`, `textarea`, `number`, `select`, `checkbox`,
|
|
77
|
+
`switch`. Kit options such as `inputType`, `rows` and `span` go into `props`.
|
|
78
|
+
- Never put functions, expressions or HTML into a definition, and never
|
|
79
|
+
build one by string concatenation: produce the object and validate it.
|
|
80
|
+
- In React a definition is read when the component mounts; give `JsonForm` a
|
|
81
|
+
`key` to show another one.
|
|
82
|
+
- `fromJsonSchema(schema)` turns a flat JSON Schema (string, number, integer,
|
|
83
|
+
boolean and enum properties) into a definition.
|
|
84
|
+
|
|
36
85
|
## Lifecycle
|
|
37
86
|
|
|
38
87
|
```ts
|
|
@@ -68,6 +117,13 @@ const form = useForm(controller); // in a component that has the controller
|
|
|
68
117
|
|
|
69
118
|
Without that package: `useSyncExternalStore(controller.subscribe, controller.getForm)`.
|
|
70
119
|
`start()` publishes the started form the same way (since 2.1).
|
|
120
|
+
|
|
121
|
+
Since 2.2 every item has `dirty` (its value differs from the initial one) and
|
|
122
|
+
`touched` (set by the `Touch` service), and a started form has
|
|
123
|
+
`form.state`: `{ dirty, touched, valid, validating, submitting, submitCount, errors }`.
|
|
124
|
+
`dirty`, `touched` and `valid` follow from the items; `errors` are the errors
|
|
125
|
+
of the form as a whole, such as a rejected submit. In React
|
|
126
|
+
`useFormState(controller)` returns it and only renders again when it changes.
|
|
71
127
|
Never change a form or an item in place; use the services.
|
|
72
128
|
|
|
73
129
|
## Services
|
|
@@ -77,7 +133,7 @@ entity of the form, so property names and results are type-checked.
|
|
|
77
133
|
|
|
78
134
|
| Class | Call |
|
|
79
135
|
|---|---|
|
|
80
|
-
| `Validate` | `run(): Promise<boolean>`, validates every
|
|
136
|
+
| `Validate` | `run(): Promise<boolean>`, validates every item that is not hidden or disabled |
|
|
81
137
|
| `Trigger` | `run(property): Promise<void>`, validates one item |
|
|
82
138
|
| `GetValues` | `run(): Promise<E>`, a copy of the entity filled with the item values |
|
|
83
139
|
| `SetValue` | `run(property, value): Promise<void>`, then runs the `control` function of the item |
|
|
@@ -85,6 +141,8 @@ entity of the form, so property names and results are type-checked.
|
|
|
85
141
|
| `ResetItem` | `run(property): Promise<void>` |
|
|
86
142
|
| `ClearError` | `run(property): Promise<void>` |
|
|
87
143
|
| `ClearErrors` | `run(): Promise<void>` |
|
|
144
|
+
| `Touch` | `run(property): Promise<void>`, marks the item as touched; call it when the user leaves the field (since 2.2) |
|
|
145
|
+
| `Submit` | `run(handler?): Promise<boolean>`, validates, then calls `handler(values)`; sets `state.submitting`, ignores a second submit meanwhile, and turns what the handler throws into `state.errors` instead of rejecting (since 2.2) |
|
|
88
146
|
| `Store` | no `run`: it adds `readStoreItem`, `writeStoreItem`, `deleteStoreItem` to the command passed to item functions (`CommandItem<E, F, StoreCommand>`) |
|
|
89
147
|
|
|
90
148
|
```ts
|
|
@@ -110,11 +168,14 @@ if (await controller.getService(Validate).run()) {
|
|
|
110
168
|
- `Validate.run()` returns `false` when the form is invalid. Other failures
|
|
111
169
|
(an unknown property, an error thrown by a validation function) reject.
|
|
112
170
|
- Setting a value does not validate it. Run `Trigger` for that.
|
|
171
|
+
- To submit a form prefer `Submit` (since 2.2) over calling `Validate` and
|
|
172
|
+
`GetValues` by hand. Do not keep your own `submitting` or `dirty` flags.
|
|
113
173
|
|
|
114
174
|
## Form items
|
|
115
175
|
|
|
116
176
|
A form item is a plain object: `property`, `label`, `type`, `value`,
|
|
117
|
-
`required`, `disabled`, `hidden`, `error`, `errorMessages
|
|
177
|
+
`required`, `disabled`, `hidden`, `error`, `errorMessages`, `dirty`,
|
|
178
|
+
`touched`, `validating`. Add the
|
|
118
179
|
properties of your form system with a type of your own:
|
|
119
180
|
`type AppItem<E> = FormItem<E> & { layout?: Layout }`, then use
|
|
120
181
|
`FormController<UserForm, AppItem<UserForm>>`.
|
|
@@ -122,7 +183,15 @@ properties of your form system with a type of your own:
|
|
|
122
183
|
The functions of an item receive a command `{ formItem, initialEntity,
|
|
123
184
|
getItem }` holding copies, and return items instead of changing them:
|
|
124
185
|
|
|
125
|
-
- `validation(command): Promise<{ error: boolean, errorMessages?: string[] }
|
|
186
|
+
- `validation(command, context?): Promise<{ error: boolean, errorMessages?: string[] }>`.
|
|
187
|
+
Since 2.2 the services pass `context.signal`, an `AbortSignal` that is
|
|
188
|
+
aborted when the item is validated again, changed or reset: give it to
|
|
189
|
+
`fetch(url, { signal: context?.signal })`. A validation that rejects after
|
|
190
|
+
it was aborted is ignored. The item is `validating` meanwhile.
|
|
191
|
+
- `validateDebounce: 300` on an item makes `Trigger` wait that many
|
|
192
|
+
milliseconds and validate once after the last trigger (since 2.2). Use it
|
|
193
|
+
for validations that ask a server while the user types; do not write your
|
|
194
|
+
own debounce around `Trigger`. `Validate` and `Submit` do not wait.
|
|
126
195
|
- `control(command): Promise<FormItem[]>`, run after its value is set; the
|
|
127
196
|
returned items are written to the form
|
|
128
197
|
- `initialize(command): Promise<FormItem[]>`, run once while the form is created
|
|
@@ -137,6 +206,8 @@ handler. Payloads are typed.
|
|
|
137
206
|
| `UPDATE_FORM` | the form; fired after every change |
|
|
138
207
|
| `UPDATE_ITEM` | an array: the changed item, then the items its `control` returned |
|
|
139
208
|
| `RESET` | the form; fired by `Reset`, after `UPDATE_FORM` |
|
|
209
|
+
| `SUBMIT` | the values the submit handler received; fired by `Submit` (since 2.2) |
|
|
210
|
+
| `SUBMIT_ERROR` | what a validation or the submit handler threw (since 2.2) |
|
|
140
211
|
| `REGISTER_ITEMS` | `string[]` of registered form item types; fired at the start of `start()` |
|
|
141
212
|
|
|
142
213
|
## A complete example
|
package/src/load.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Reads the type declarations of a Punica Form package from disk: the copy
|
|
2
2
|
// installed in the project the server is started in, so the answers match
|
|
3
3
|
// that version; without one, the copy bundled with this server.
|
|
4
|
-
import { readdirSync, readFileSync } from 'node:fs';
|
|
4
|
+
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
|
5
5
|
import { createRequire } from 'node:module';
|
|
6
6
|
import { dirname, join, relative, sep } from 'node:path';
|
|
7
7
|
import { fileURLToPath } from 'node:url';
|
|
@@ -28,7 +28,8 @@ export function readTypes(root) {
|
|
|
28
28
|
* @param {string} [cwd] - The project to look for the package in
|
|
29
29
|
* @param {string} [entry] - A second entry point of the package, such as
|
|
30
30
|
* `react` for `@punica/form-kit/react`
|
|
31
|
-
* @returns {{ name: string, version: string, files: Map<string, string>, installed: boolean }}
|
|
31
|
+
* @returns {{ name: string, version: string, files: Map<string, string>, installed: boolean } | undefined}
|
|
32
|
+
* `undefined` for an entry point the installed version does not have
|
|
32
33
|
*/
|
|
33
34
|
export function loadPackage(name, cwd = process.cwd(), entry = '') {
|
|
34
35
|
const entryName = entry ? `${name}/${entry}` : name;
|
|
@@ -39,6 +40,10 @@ export function loadPackage(name, cwd = process.cwd(), entry = '') {
|
|
|
39
40
|
const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
|
|
40
41
|
const root = join(dirname(join(dirname(manifestPath), manifest.types)), entry);
|
|
41
42
|
|
|
43
|
+
// An installed version from before the entry point existed: the project
|
|
44
|
+
// cannot import it, so it is not part of what the server knows
|
|
45
|
+
if (entry && !existsSync(root)) return undefined;
|
|
46
|
+
|
|
42
47
|
return { name: entryName, version: manifest.version, files: readTypes(root), installed: true };
|
|
43
48
|
} catch {
|
|
44
49
|
const root = join(BUNDLED, name.split('/')[1]);
|
package/src/main.mjs
CHANGED
|
@@ -10,8 +10,10 @@ const packages = [
|
|
|
10
10
|
loadPackage('@punica/form-service'),
|
|
11
11
|
loadPackage('@punica/form-react'),
|
|
12
12
|
loadPackage('@punica/form-kit'),
|
|
13
|
-
loadPackage('@punica/form-kit', process.cwd(), 'react')
|
|
14
|
-
|
|
13
|
+
loadPackage('@punica/form-kit', process.cwd(), 'react'),
|
|
14
|
+
loadPackage('@punica/form-kit', process.cwd(), 'json'),
|
|
15
|
+
loadPackage('@punica/form-json')
|
|
16
|
+
].filter(Boolean);
|
|
15
17
|
const guide = readFileSync(new URL('./guide.md', import.meta.url), 'utf8');
|
|
16
18
|
|
|
17
19
|
const server = createPunicaFormServer({ packages, guide });
|