@punica/form-mcp 0.4.0-next.1 → 0.5.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.
@@ -1 +1 @@
1
- {"version":"2.2.0-next.1"}
1
+ {"version":"2.3.0"}
@@ -1 +1 @@
1
- {"version":"0.1.0-next.0"}
1
+ {"version":"0.2.0"}
@@ -9,7 +9,7 @@ export type FormKitOptions = {
9
9
  columns?: 1 | 2 | 3 | 4;
10
10
  /**
11
11
  * Services in addition to GetValues, SetValue, Validate, Trigger, Reset,
12
- * Touch, Submit and FieldArray.
12
+ * Touch, Submit, FieldArray and SetErrors.
13
13
  */
14
14
  services?: Array<IService | (new () => IService)>;
15
15
  /** Readers in addition to the kit's. */
@@ -1 +1 @@
1
- {"version":"0.3.0-next.1"}
1
+ {"version":"0.4.0"}
@@ -1 +1 @@
1
- {"version":"0.2.0-next.1"}
1
+ {"version":"0.2.0"}
@@ -1 +1 @@
1
- {"version":"0.1.0-next.0"}
1
+ {"version":"0.1.0"}
@@ -5,6 +5,7 @@ import type { FieldArray } from './fieldArray';
5
5
  import type { GetValues } from './getValues';
6
6
  import type { Reset } from './reset';
7
7
  import type { ResetItem } from './resetItem';
8
+ import type { SetErrors } from './setErrors';
8
9
  import type { SetValue } from './setValue';
9
10
  import type { Submit } from './submit';
10
11
  import type { Touch } from './touch';
@@ -20,6 +21,7 @@ export type { FormRow } from './rows';
20
21
  export * from './getValues';
21
22
  export * from './reset';
22
23
  export * from './resetItem';
24
+ export * from './setErrors';
23
25
  export * from './setValue';
24
26
  export * from './store';
25
27
  export * from './submit';
@@ -34,6 +36,7 @@ declare module '@punica/form' {
34
36
  getValues: GetValues<E, F>;
35
37
  reset: Reset<E, F>;
36
38
  resetItem: ResetItem<E, F>;
39
+ setErrors: SetErrors<E, F>;
37
40
  setValue: SetValue<E, F>;
38
41
  submit: Submit<E, F>;
39
42
  touch: Touch<E, F>;
@@ -1 +1 @@
1
- {"version":"2.2.0-next.1"}
1
+ {"version":"2.3.0"}
@@ -26,6 +26,13 @@ export declare const rowsOf: (command: object, property: PropertyKey) => readonl
26
26
  export declare const createLists: <E, F extends FormItem<E>>(command: CommandService<E, F>, validate: new () => IService & {
27
27
  run: () => Promise<boolean>;
28
28
  }) => Promise<void>;
29
+ /**
30
+ * Shows an error on the item of a list itself, as its own validation would:
31
+ * it stays while the rows change and goes when the list is validated again,
32
+ * cleared or reset.
33
+ * @returns `false` when the item of the property is not a list
34
+ */
35
+ export declare const setListError: <E, F extends FormItem<E>>(command: CommandService<E, F>, property: keyof E, errorMessages: string[]) => boolean;
29
36
  /**
30
37
  * Wraps the validations of the items of a form, for a service that adds a
31
38
  * validation of its own to them. It works with lists whatever the order of
@@ -0,0 +1,46 @@
1
+ import { CommandService, FormItem, IServiceControl, IServiceInitialize } from '@punica/form';
2
+ /**
3
+ * Messages by item, as a server sends them for what it refused. A name is a
4
+ * property of the form; `lines.1.price` (or `lines[1].price`) is the item
5
+ * `price` of the second row of the list `lines`. Nested objects and arrays
6
+ * say the same: `{ lines: [{}, { price: ['Too high'] }] }`.
7
+ */
8
+ export type ItemErrors = {
9
+ readonly [name: string]: string | readonly string[] | ItemErrors | unknown;
10
+ };
11
+ /**
12
+ * Shows errors that were found outside the form, by a server for example,
13
+ * on the items they are about.
14
+ *
15
+ * ```ts
16
+ * try {
17
+ * await save(values);
18
+ * } catch (error) {
19
+ * // { email: ['This email is already registered'], capacity: ['Full'] }
20
+ * const rest = await controller.getService(SetErrors).run(error.fields);
21
+ *
22
+ * if (rest.length) throw new Error(rest.join(' ')); // shown by the form
23
+ * }
24
+ * ```
25
+ *
26
+ * An error set this way replaces the messages its item had. It goes when
27
+ * the item is validated again (`Trigger`, `Validate`, `Submit`), also when
28
+ * the item has no validation of its own, and with `ClearError`,
29
+ * `ClearErrors`, `ResetItem` and `Reset`. A validation that was running
30
+ * when the error was set does not erase it.
31
+ */
32
+ export declare class SetErrors<E, F extends FormItem<E> = FormItem<E>> implements IServiceInitialize<E, F>, IServiceControl {
33
+ #private;
34
+ get name(): string;
35
+ initialize(command: CommandService<E, F>): void;
36
+ /**
37
+ * Writes the messages onto the items they name. The rows of a list are
38
+ * reached through their index.
39
+ * @param errors - Messages by item: see `ItemErrors`. What is no object
40
+ * of messages (a text, `null`) names no item
41
+ * @returns The messages that are about no item of the form, to be shown
42
+ * for the form as a whole; those of a row stand where the row was first
43
+ * named
44
+ */
45
+ run(errors: ItemErrors | unknown): Promise<string[]>;
46
+ }
@@ -5,6 +5,16 @@ import { CommandService, FormItem } from '@punica/form';
5
5
  * and their results are not written.
6
6
  */
7
7
  export declare const dropValidations: <E, F extends FormItem<E>>(command: CommandService<E, F>, property?: keyof E) => void;
8
+ /**
9
+ * Notes that the error of a property was set from outside, by `SetErrors`.
10
+ *
11
+ * A validation of the property that is running, or waiting for its delay,
12
+ * is cancelled: what it finds was asked before the error was known and must
13
+ * not erase it. A validation that starts afterwards replaces the error, and
14
+ * so the error of an item that is not validated at all (no validation,
15
+ * hidden, disabled) goes when the item is asked to be validated.
16
+ */
17
+ export declare const noteExternalError: <E, F extends FormItem<E>>(command: CommandService<E, F>, property: keyof E) => void;
8
18
  /**
9
19
  * Waits for the delay of a validation (`validateDebounce` of the item).
10
20
  * @returns Whether to validate: `false` when the property was validated,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@punica/form-mcp",
3
- "version": "0.4.0-next.1",
3
+ "version": "0.5.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,15 +36,15 @@
36
36
  },
37
37
  "dependencies": {
38
38
  "@modelcontextprotocol/sdk": "^1.32.2",
39
- "@punica/form-json": "^0.1.0-next.0",
39
+ "@punica/form-json": "^0.2.0",
40
40
  "zod": "^4.6.7"
41
41
  },
42
42
  "devDependencies": {
43
- "@punica/form": "^2.2.0-next.1",
44
- "@punica/form-service": "^2.2.0-next.1",
45
- "@punica/form-react": "^0.2.0-next.1",
46
- "@punica/form-kit": "^0.3.0-next.1",
47
- "@punica/form-schema": "^0.1.0-next.0"
43
+ "@punica/form": "^2.3.0",
44
+ "@punica/form-service": "^2.3.0",
45
+ "@punica/form-react": "^0.2.0",
46
+ "@punica/form-kit": "^0.4.0",
47
+ "@punica/form-schema": "^0.1.0"
48
48
  },
49
49
  "scripts": {
50
50
  "build": "node build.mjs",
package/src/guide.md CHANGED
@@ -16,7 +16,7 @@ Punica Form is a headless form engine. `@punica/form` holds the engine,
16
16
  or Yup; see "Validation with a schema" below.
17
17
  - `@punica/form-service`: `Validate`, `GetValues`, `SetValue`, `Reset`,
18
18
  `ResetItem`, `Trigger`, `ClearError`, `ClearErrors`, `Touch`, `Submit`,
19
- `FieldArray`, `Store`.
19
+ `SetErrors`, `FieldArray`, `Store`.
20
20
  - NOT provided: `@Title`, `@Description`, `@Layout`, `@FormItemInputText` or
21
21
  any other form item decorator, a `Reader` class, a base form item. These
22
22
  belong to the application's own form system. Build them with the `define*`
@@ -33,18 +33,20 @@ Punica Form is a headless form engine. `@punica/form` holds the engine,
33
33
  call:
34
34
 
35
35
  ```ts
36
- import { defineForm, field, Services } from "@punica/form";
36
+ import { defineForm, field, Services } from '@punica/form';
37
37
 
38
38
  const UserForm = defineForm(
39
39
  {
40
- name: field("", Text({ label: "Name" })),
41
- age: field<number | undefined>(undefined, NumberInput({ label: "Age" })),
40
+ name: field('', Text({ label: 'Name' })),
41
+ age: field<number | undefined>(undefined, NumberInput({ label: 'Age' }))
42
42
  },
43
43
  Services([GetValues, SetValue]) // or FormKit({ title: "User" })
44
44
  );
45
45
  type User = InstanceType<typeof UserForm>;
46
46
 
47
- const controller = await FormController.fromEntity(new UserForm({ name: "Jane" }));
47
+ const controller = await FormController.fromEntity(
48
+ new UserForm({ name: 'Jane' })
49
+ );
48
50
  ```
49
51
 
50
52
  The result is a form class like a decorated one; do not mix both styles in
@@ -110,7 +112,7 @@ The form is immutable. Every change produces a new form object; items that
110
112
  did not change keep their identity.
111
113
 
112
114
  ```ts
113
- controller.getForm(); // the current form
115
+ controller.getForm(); // the current form
114
116
  const unsubscribe = controller.subscribe(() => {}); // after every change
115
117
  ```
116
118
 
@@ -138,26 +140,27 @@ Never change a form or an item in place; use the services.
138
140
  Services are read by class and executed with `run`. They are bound to the
139
141
  entity of the form, so property names and results are type-checked.
140
142
 
141
- | Class | Call |
142
- |---|---|
143
- | `Validate` | `run(): Promise<boolean>`, validates every item that is not hidden or disabled |
144
- | `Trigger` | `run(property): Promise<void>`, validates one item |
145
- | `GetValues` | `run(): Promise<E>`, a copy of the entity filled with the item values |
146
- | `SetValue` | `run(property, value): Promise<void>`, then runs the `control` function of the item |
147
- | `Reset` | `run(): Promise<void>` |
148
- | `ResetItem` | `run(property): Promise<void>` |
149
- | `ClearError` | `run(property): Promise<void>` |
150
- | `ClearErrors` | `run(): Promise<void>` |
151
- | `Touch` | `run(property): Promise<void>`, marks the item as touched; call it when the user leaves the field (since 2.2) |
152
- | `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) |
153
- | `FieldArray` | no `run`: `rows(property)`, `append`, `insert`, `remove`, `move`, `replace`; see "Lists of rows" (since 2.2) |
154
- | `Store` | no `run`: it adds `readStoreItem`, `writeStoreItem`, `deleteStoreItem` to the command passed to item functions (`CommandItem<E, F, StoreCommand>`) |
143
+ | Class | Call |
144
+ | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
145
+ | `Validate` | `run(): Promise<boolean>`, validates every item that is not hidden or disabled |
146
+ | `Trigger` | `run(property): Promise<void>`, validates one item |
147
+ | `GetValues` | `run(): Promise<E>`, a copy of the entity filled with the item values |
148
+ | `SetValue` | `run(property, value): Promise<void>`, then runs the `control` function of the item |
149
+ | `Reset` | `run(): Promise<void>` |
150
+ | `ResetItem` | `run(property): Promise<void>` |
151
+ | `ClearError` | `run(property): Promise<void>` |
152
+ | `ClearErrors` | `run(): Promise<void>` |
153
+ | `Touch` | `run(property): Promise<void>`, marks the item as touched; call it when the user leaves the field (since 2.2) |
154
+ | `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) |
155
+ | `SetErrors` | `run(errors): Promise<string[]>`, shows messages found outside the form (by a server) on the items they name; returns those that name no item (since 2.3) |
156
+ | `FieldArray` | no `run`: `rows(property)`, `append`, `insert`, `remove`, `move`, `replace`; see "Lists of rows" (since 2.2) |
157
+ | `Store` | no `run`: it adds `readStoreItem`, `writeStoreItem`, `deleteStoreItem` to the command passed to item functions (`CommandItem<E, F, StoreCommand>`) |
155
158
 
156
159
  ```ts
157
- import { GetValues, SetValue, Trigger, Validate } from "@punica/form-service";
160
+ import { GetValues, SetValue, Trigger, Validate } from '@punica/form-service';
158
161
 
159
- await controller.getService(SetValue).run("name", "Jane");
160
- await controller.getService(Trigger).run("name");
162
+ await controller.getService(SetValue).run('name', 'Jane');
163
+ await controller.getService(Trigger).run('name');
161
164
 
162
165
  if (await controller.getService(Validate).run()) {
163
166
  const values = await controller.getService(GetValues).run();
@@ -178,6 +181,31 @@ if (await controller.getService(Validate).run()) {
178
181
  - Setting a value does not validate it. Run `Trigger` for that.
179
182
  - To submit a form prefer `Submit` (since 2.2) over calling `Validate` and
180
183
  `GetValues` by hand. Do not keep your own `submitting` or `dirty` flags.
184
+ - When a server refuses what was submitted with messages by field, show them
185
+ with `SetErrors` (since 2.3) instead of writing items yourself, and throw
186
+ the rest so the form shows it:
187
+
188
+ ```ts
189
+ await controller.getService(Submit).run(async (values) => {
190
+ try {
191
+ await save(values);
192
+ } catch (error) {
193
+ // { email: ["Already registered"], "lines.1.price": ["Too high"], capacity: ["Full"] }
194
+ const rest = await controller
195
+ .getService(SetErrors)
196
+ .run(fieldErrorsOf(error));
197
+
198
+ throw new Error(rest.join(' ') || 'Correct the marked fields.');
199
+ }
200
+ });
201
+ ```
202
+
203
+ A name is a property; `lines.1.price` is an item of a row of a list, and
204
+ nested objects (`{ lines: [{}, { price: ["Too high"] }] }`) say the same.
205
+ Such an error goes when its item is validated again (`Trigger`, `Validate`,
206
+ `Submit`), cleared or reset; a validation that was running when it was set
207
+ does not erase it. `@FormKit`, `fromSchema` and `JsonForm` list `SetErrors`
208
+ already; a form with its own `@Services` has to list it.
181
209
 
182
210
  ## Lists of rows
183
211
 
@@ -273,18 +301,41 @@ class UserForm { … }
273
301
  `addFormValidation(command, () => messages)` of `@punica/form-service` in
274
302
  its `initialize` (since 2.2).
275
303
 
304
+ ## With the other Punica libraries
305
+
306
+ Punica Form is one of three libraries made to be used together: Punica
307
+ Request (`@punica/request`, the HTTP client) and Punica Components
308
+ (`@punica/components`, the elements the kit renders with). Each has an MCP
309
+ server; when the project has them, look their APIs up there instead of
310
+ guessing. Where they meet:
311
+
312
+ - **Choices from a server**: `options: () => listCountries()` of a kit field
313
+ may return a promise; give it a function that asks the client.
314
+ - **A validation that asks a server**: pass `context.signal` on as the
315
+ `signal` of the request, and set `validateDebounce`. A request for a value
316
+ the user typed over is cancelled.
317
+ - **What a server refuses**: a failed request of Punica Request rejects with
318
+ an `HttpError` whose `response.data` is the body the server sent. Give its
319
+ messages by field to `SetErrors` and throw the rest, as shown above.
320
+ - **Submitting**: do the request inside the handler of `Submit` (or
321
+ `onSubmit` of `KitForm`); the form shows that it is submitting and keeps a
322
+ second submit out.
323
+
324
+ A whole application on the three, with its tests:
325
+ https://github.com/punicalab/punica-starter (start with its `AGENTS.md`).
326
+
276
327
  ## Events
277
328
 
278
329
  `controller.on(event, handler)` returns the function that removes the
279
330
  handler. Payloads are typed.
280
331
 
281
- | Event | Payload |
282
- |---|---|
283
- | `UPDATE_FORM` | the form; fired after every change |
284
- | `UPDATE_ITEM` | an array: the changed item, then the items its `control` returned |
285
- | `RESET` | the form; fired by `Reset`, after `UPDATE_FORM` |
286
- | `SUBMIT` | the values the submit handler received; fired by `Submit` (since 2.2) |
287
- | `SUBMIT_ERROR` | what a validation or the submit handler threw (since 2.2) |
332
+ | Event | Payload |
333
+ | ---------------- | ------------------------------------------------------------------------- |
334
+ | `UPDATE_FORM` | the form; fired after every change |
335
+ | `UPDATE_ITEM` | an array: the changed item, then the items its `control` returned |
336
+ | `RESET` | the form; fired by `Reset`, after `UPDATE_FORM` |
337
+ | `SUBMIT` | the values the submit handler received; fired by `Submit` (since 2.2) |
338
+ | `SUBMIT_ERROR` | what a validation or the submit handler threw (since 2.2) |
288
339
  | `REGISTER_ITEMS` | `string[]` of registered form item types; fired at the start of `start()` |
289
340
 
290
341
  ## A complete example
@@ -298,44 +349,46 @@ import {
298
349
  getFormProperty,
299
350
  type Form,
300
351
  type FormItem,
301
- type IReader,
302
- } from "@punica/form";
352
+ type IReader
353
+ } from '@punica/form';
303
354
 
304
- export const Title = defineFormProperty<string>("app:title");
355
+ export const Title = defineFormProperty<string>('app:title');
305
356
 
306
- export class Reader<E extends object, F extends FormItem<E>> implements IReader<E, F> {
357
+ export class Reader<E extends object, F extends FormItem<E>> implements IReader<
358
+ E,
359
+ F
360
+ > {
307
361
  public read(entity: E, form: Form<E, F>): void {
308
- form.title = getFormProperty<string>(entity, "app:title");
362
+ form.title = getFormProperty<string>(entity, 'app:title');
309
363
  }
310
364
  }
311
365
 
312
366
  // The second argument is the renderer; defaultFormItemRegister.getItem(item.type) returns it
313
- export const FormItemInputText = defineFormItem<Omit<FormItem<any>, "property">>(
314
- "app:input-text",
315
- InputText
316
- );
367
+ export const FormItemInputText = defineFormItem<
368
+ Omit<FormItem<any>, 'property'>
369
+ >('app:input-text', InputText);
317
370
  ```
318
371
 
319
372
  A business form:
320
373
 
321
374
  ```ts
322
- import { Readers, Services } from "@punica/form";
323
- import { GetValues, SetValue, Trigger, Validate } from "@punica/form-service";
324
- import { FormItemInputText, Reader, Title } from "./formSystem";
375
+ import { Readers, Services } from '@punica/form';
376
+ import { GetValues, SetValue, Trigger, Validate } from '@punica/form-service';
377
+ import { FormItemInputText, Reader, Title } from './formSystem';
325
378
 
326
- @Title("Create User")
379
+ @Title('Create User')
327
380
  @Readers([new Reader()])
328
381
  @Services([GetValues, SetValue, Validate, Trigger])
329
382
  export class UserForm {
330
383
  @FormItemInputText({
331
- label: "Name",
384
+ label: 'Name',
332
385
  required: true,
333
386
  validation: async ({ formItem }) => ({
334
387
  error: !formItem.value,
335
- errorMessages: formItem.value ? [] : ["Name is required"],
336
- }),
388
+ errorMessages: formItem.value ? [] : ['Name is required']
389
+ })
337
390
  })
338
- name = "";
391
+ name = '';
339
392
  }
340
393
  ```
341
394
 
@@ -347,7 +400,7 @@ const controller = await FormController.fromEntity(new UserForm());
347
400
  controller.subscribe(() => render(controller.getForm()));
348
401
  await controller.start();
349
402
 
350
- await controller.getService(SetValue).run("name", "Jane");
403
+ await controller.getService(SetValue).run('name', 'Jane');
351
404
 
352
405
  if (await controller.getService(Validate).run()) {
353
406
  const values = await controller.getService(GetValues).run(); // UserForm
package/src/knowledge.mjs CHANGED
@@ -40,7 +40,23 @@ function declarationAt(source, index) {
40
40
 
41
41
  function entry(source, index, kind, name) {
42
42
  const comment = commentBefore(source, index);
43
- const summary = (/^\s*\/?\*+\s*([^@*\n][^\n]*)/m.exec(comment) || [])[1] || '';
43
+ // The first paragraph of the comment, without its stars, up to the end of
44
+ // its first sentence
45
+ const lines = comment
46
+ .replace(/^\s*\/\*+/, '')
47
+ .replace(/\*+\/\s*$/, '')
48
+ .split('\n')
49
+ .map((line) => line.replace(/^\s*\*+\s?/, '').trim());
50
+ const start = lines.findIndex((line) => line && !line.startsWith('@'));
51
+ const paragraph = [];
52
+
53
+ for (let i = start; i >= 0 && i < lines.length; i++) {
54
+ if (!lines[i] || lines[i].startsWith('@') || lines[i].startsWith('```')) break;
55
+ paragraph.push(lines[i]);
56
+ }
57
+
58
+ const text = paragraph.join(' ');
59
+ const summary = (/^.*?[.:](?=\s|$)/.exec(text)?.[0] ?? text).replace(/:$/, '.');
44
60
 
45
61
  return {
46
62
  name,