suppa-mcp-2 1.44.4 → 1.45.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.
@@ -0,0 +1,174 @@
1
+ # Code Form — writing a form's code (FormBuilder 2.x)
2
+
3
+ A FormBuilder 2.x form can carry code: TypeScript files under `src/**` (entry `src/index.ts`) written against ONE
4
+ typed global, `formAPI` — the form's elements, variables, services, events, windows and submit. The builder's code
5
+ editor type-checks it against the SDK and the form's own generated types; on every save the SERVER builds it into
6
+ the artifact the runtime executes. Tools: `suppa_form_code` (rules · pull · api · check) and `suppa_push_form_code`.
7
+
8
+ Sources: the front's `docs/formBuilder/features/code-form.md` and `codeform-sdk.md`, the formbuilder agent's prompt
9
+ and compile gate (suppa-ai-agent `formbuilder-agent`), the fb-live MCP's Code Form workflow, and entity-builder's
10
+ form save (`form-schema.service.ts`). The SDK typings and the type generator are vendored from the front
11
+ (`code-form/SOURCE.json` names the commit).
12
+
13
+ ## Rules
14
+
15
+ 1. **Prefer no code.** Show / hide / enable / disable / required-by-condition is a declarative condition on the
16
+ element (`suppa_form_kb mode='ref' topic='conditions'`) — it needs no code and always works. Code is for
17
+ cross-field computation, actions, requests and submit-gating.
18
+ 2. **Learn the API from the types, never from memory.** `suppa_form_code mode='api'`: `path='formAPI.elements.<name>'`
19
+ for an element of this form, `type='<elementType>'` for any type, `'formAPI'`, `'formAPI.services.ui'`,
20
+ `'formAPI.utils'` for the rest; `member='<name>'` for one member with every overload and its whole doc. A member
21
+ the types do not have does not exist — the editor marks it, and the server build may fail on it.
22
+ 3. **Events only from the type.** `api` lists the events `on(name, …)` takes for that element. An invented name
23
+ COMPILES (a catch-all overload) and the handler never runs — `check` warns `unknown-event`. Form-level events are
24
+ strictly typed: `ready`, `beforeSubmit`, `afterSubmit`, `beforeDestroy`, `elementValueChanged`, `realtime`,
25
+ `headerAction`, `hostMessage`, `layoutChanged`.
26
+ 4. **`before*` hooks are gates, not notifications.** They run in order and are awaited; return `false` or call
27
+ `ctx.cancel()` to veto; writable `ctx` fields transform the action. `beforeSubmit` returning `false` blocks the
28
+ submit. Register them on the element (`el.on('beforeCellOpen', fn)`).
29
+ 5. **A field-level problem is `setError(message)` / `clearError()` on the element** — a toast
30
+ (`services.ui.notify`) neither marks the field nor blocks submit.
31
+ 6. **Two presentations, one code.** On a form with a mobile layout an element that exists in only one of them is
32
+ `T | undefined`: reach it with `?.` or inside `if (formAPI.presentation === 'desktop')`. An unguarded call throws
33
+ on the other presentation and every statement after it in the module is lost.
34
+ 7. **`formAPI.form.type` is live, `formAPI.context.mode` is frozen.** After a `submit()` of a create card,
35
+ `form.type` says `update` while `context.mode` still says `create` — branch on `form.type` for "is it saved yet".
36
+ 8. **Imports: relative (`./`, `../`), type-only `@suppa/frontend-sdk`, and `@shared/<name>` only where it already
37
+ is.** Helpers use NAMED exports. Anything else is an error in the editor (`check` reports `import`).
38
+ 9. **A file that imports a tenant shared module (`@shared/…`) is READ-ONLY** — byte for byte. Make the change in
39
+ another file; call what that file exports, but never use its shared import's bindings elsewhere, and never add,
40
+ rename or move a shared-module import (its code is invisible to every check, runs on import in every viewer's
41
+ browser, and a public form's anonymous visitor cannot load it). `suppa_push_form_code` refuses both.
42
+ 10. **No browser globals.** The sandbox's types have no DOM: `window`, `document`, `localStorage`, `location`,
43
+ `navigator`, `open`, `alert` / `confirm` / `prompt`, `eval`, `Function`, `globalThis`, `Reflect`, `Proxy`,
44
+ `WebSocket`, `postMessage`… are errors or `denied-global` warnings. Use the platform: `services.ui.notify` /
45
+ `.confirm`, `formAPI.navigate`, `formAPI.openForm`, `services.storage`, `formAPI.realtime.subscribe`. There is no
46
+ API for a new browser tab or the clipboard except `formAPI.header.copyLink()` (this record's link) — use a
47
+ declarative link option (`menuPanelItem` `openInNewTab`) or say it cannot be done.
48
+ 11. **`fetch` is for THIRD-PARTY origins only** (a public API, a signed upload URL). The tenant's own data goes
49
+ through `formAPI.services.api.*` — it carries the auth, the request cache and its invalidation. A 4xx/5xx
50
+ resolves: check `response.ok`.
51
+ 12. **Never touch an element's `schema`, `customView` or `compiledRender`** — read or write, `Object.assign`
52
+ included. It holds widget code the page recompiles with full page access; drive an element through its methods.
53
+ 13. **Copy form values with `formAPI.utils.object.deepClone(v)`, not `structuredClone`** — form values are Vue
54
+ reactive proxies and `structuredClone` throws `DataCloneError` on them at runtime while the editor is green.
55
+ 14. **No `debugger`**, no busy loops. Timers (`setTimeout` / `setInterval`) are bound to the form's life since
56
+ 2026-09-18; still clear what you start.
57
+ 15. **A green check is not a working form.** The server builds with ITS SDK copy — the push answers with the build
58
+ result, and only a clean build runs. Then open the draft and try the behaviour.
59
+ 16. **Nothing is published by these tools.** The draft changes (a published form reads `editing`); users see the
60
+ code after a publish (`suppa_form_lifecycle`), on the user's word.
61
+
62
+ ## Workflow
63
+
64
+ 1. `suppa_form_code mode='rules'` once (this section), `topic='<word>'` for another section.
65
+ 2. `mode='pull' form_id=N` — the DRAFT's own code into `<workspace>/<host>/form-N/`: `src/**` to edit with your file
66
+ tools; `generated/` (this form's `formAPI` type, the environment, the shared-module stub),
67
+ `node_modules/@suppa/frontend-sdk/index.d.ts` and `tsconfig.json` (the editor's options) to check against;
68
+ `.suppa-code/manifest.json` remembers what each file held — the base a push is judged against. A pull refuses to
69
+ overwrite edits not pushed yet (`force=true` discards them).
70
+ 3. `mode='api'` for every element and member you are about to use.
71
+ 4. Edit `src/**`. An element the code needs must exist first: add it to the form (`suppa_write_form_draft`), then
72
+ `check` — it re-types the workspace from the draft as it is now.
73
+ 5. `mode='check'` until it is clean: type errors are the editor's; `import`, `denied-global`, `forbidden-member`,
74
+ `unknown-event`, `fetch`, `debugger` are this server's (warnings except `import`). It also says when the tenant's
75
+ draft no longer matches your last sync, and what a push would refuse.
76
+ 6. `suppa_push_form_code form_id=N` → the plan; `confirm=true` → the save. It re-reads the draft, re-checks, and sends
77
+ ONLY `code` with `expectedRevision` — schema, settings, variables and texts are untouched.
78
+ 7. Read the answer: `✓ the server built it`, or `✗ BUILD FAILED` with the compiler's messages — fix and push again.
79
+ 8. Open the draft, try the behaviour; publish only when the user says so.
80
+
81
+ A session that cannot see the workspace folder: `pull inline=true` prints the files, and
82
+ `suppa_push_form_code files=[{ path, content }]` writes them into `src/` before the push (`content: null` deletes).
83
+
84
+ ## Conflicts
85
+
86
+ The builder and other people save the same form. A push compares each file you changed with the draft as it is
87
+ now: a file someone else saved after your pull is a conflict — NOTHING is saved, their version goes to
88
+ `.suppa-code/conflicts/<path>` and becomes the base. Merge it into `src/` (keep both sides' intent) and push again.
89
+ Pushing your refused version unchanged is refused again; `overwrite=['<path>']` replaces theirs on purpose — only
90
+ when the user agrees. The builder reformats every file with Prettier on its save, so after a person saves the form,
91
+ pull before you edit.
92
+
93
+ Someone else's open builder (`lockedBy`) refuses the save: writing under them loses one of the two edits. Your own
94
+ open builder tab is a note — its next save overwrites this one without a warning.
95
+
96
+ ## Saving and the build
97
+
98
+ `PUT /core/forms/:id/schema` with `code` builds the files with esbuild on the server (no type-check; the import
99
+ whitelist; at most 512 KiB of input; 10 s). The save itself always lands — a failed build answers `200` with
100
+ `buildErrors: [{ file?, line?, message }]`, keeps the PREVIOUS artifact (or none) and the form runs that. The usual
101
+ cause is SDK drift: code that uses a member the backend's SDK copy does not have yet (the editor's typings are newer)
102
+ — `element.setError()` broke the task card 189 that way in August 2026 and switched its whole code off for a day.
103
+ To rebuild, save the code again (any PUT with `code`); check `codeArtifact.builtAt` on the draft. `?mode=published`
104
+ is a separate snapshot: rebuilding the draft does not fix the published version — that needs a publish.
105
+
106
+ `pull` says the build state of the draft: built at …, or `⚠ the draft has code but NO compiled build` — then the form
107
+ runs none of its code, and a push rebuilds it.
108
+
109
+ ## Inheritance and copies
110
+
111
+ A child form (a workspace form over its base) has its OWN code; the ancestors' builds run too, root first, before
112
+ its own — `pull` names them. Its `formAPI` is typed against the MERGED tree (`effective-schema`), as the builder does.
113
+
114
+ A DETACHED form carries each ancestor's code as files under `src/inherited/f<id>/`, run from `src/index.ts` through
115
+ `import './inherited/f<id>/src/index';` lines. The tenant marks such a file with `origin` (`pull` lists them as
116
+ untouched or already edited). Read them; edit one only when the user asks to change THAT behaviour — an edited copy
117
+ is the author's own code and a later detach no longer refreshes it. Never drop or reorder those import lines on your
118
+ own; removing a copy means deleting all its files AND its import line in the same push. A file under
119
+ `src/inherited/` WITHOUT `origin` is the author's own.
120
+
121
+ ## The contract in two screens
122
+
123
+ ```ts
124
+ interface FormCodeAPI<TElements, TVariables> {
125
+ readonly presentation: 'desktop' | 'mobile';
126
+ readonly elements: TElements; // by name; a missing element is undefined
127
+ readonly variables: TVariables; // getValue() / setValue(v) / reset() / onChange(fn)
128
+ readonly services: FormCodeServices; // request, validation, ui, storage, realtime, api, …
129
+ readonly realtime: FormCodeRealtimeApi; // subscribe(entity, { insert?, update?, delete? }) — dies with the form
130
+ readonly i18n: FormI18nApi; // locale, t(key, params?), plural(key, n), exists(key)
131
+ readonly utils: FormCodeUtilities; // string, number, date, duration, array, object.deepClone, file, …
132
+ readonly header: FormHeaderApi; // setColor / setTitle / setTrayTitle / setTrayIcon / copyLink()
133
+ readonly form: FormStateApi; // live: type / isLoaded / isDirty / isValid / isReadonly / layout
134
+ readonly context: FormCodeContext; // frozen: formId, mode, entityName, instanceId, currentUser, permissions
135
+ readonly query: …; // enum VALUES for query payloads: query.comparator.In, query.operator.And
136
+ getElement(name | { by: 'id', … }); getVariable(key);
137
+ on(event, handler); // the form events of rule 3
138
+ emitAsync(…); // awaits handlers in order, returns their results
139
+ openForm(target, options?): Promise<OpenFormHandle>; // by name, alias or { entity, recordId }; handle.result
140
+ openComponent(name, options?): Promise<OpenComponentHandle>;
141
+ submit(options?): Promise<FormSubmitResult>; // status: submitted / partial / invalid / failed / cancelled
142
+ promptFields(request): Promise<Record<string, unknown> | null>;
143
+ close(result?); emitToHost(name, payload?); navigate(url, { newTab? }); submitted(mode, record);
144
+ }
145
+ // An element: getValue / setValue, setVisible / setReadonly / setRequired / setDisabled, setError / clearError,
146
+ // on / once, reveal / scrollIntoView / revealAndAdd, query(selector) inside its own subtree.
147
+ ```
148
+
149
+ ```ts
150
+ formAPI.elements.title.on('valueChanged', e => formAPI.elements.saveButton.setReadonly(!e.value));
151
+ if (formAPI.form.type === 'create') formAPI.elements.title.setValue('New task');
152
+ formAPI.on('beforeSubmit', () => {
153
+ const start = formAPI.elements.start.getValue(), end = formAPI.elements.end.getValue();
154
+ if (start && end && end < start) { formAPI.elements.end.setError('End is before start'); return false; }
155
+ });
156
+ const handle = await formAPI.openForm({ entity: 'Tasks', recordId: 39284 });
157
+ const outcome = await handle.result; // { status: 'submitted' | 'closed' | 'notFound', data }
158
+ ```
159
+
160
+ Query payloads use the enum VALUES from `formAPI.query` — a bare literal (`operator: 'and'`) is a compile error,
161
+ `formAPI.query.operator.And` is not. A `table` element takes appearance from code (`setConditionalFormats`,
162
+ `setCellStyle(s)`) and view control on `el.tableApi?.` (nullable until the grid mounts) — all transient.
163
+
164
+ ## Typings and the check
165
+
166
+ The editor's program: `lib: ['es2023']`, `strict`, `target ES2020`, `module ESNext`, no DOM lib; the SDK as
167
+ `@suppa/frontend-sdk`; the form's `globals.d.ts` (`CurrentFormElements`, `CurrentFormVariables`, `CurrentFormAPI`,
168
+ `declare global { const formAPI }`) generated from its elements and variables; `environment.d.ts` declaring only
169
+ `console`, the timers, `structuredClone` and a narrow `fetch`; `declare module '@shared/*'`. The workspace's
170
+ `tsconfig.json` is exactly these options, so `tsc -p <workspace>` reproduces `check`.
171
+
172
+ The vendored SDK is a snapshot of the front (`code-form/SOURCE.json`). A member the tenant's front has and this copy
173
+ lacks is a false error here — `allow_errors=true` on the push saves anyway; say so to the user. The reverse (a member
174
+ this copy has and the backend lacks) passes here and fails the server build: the push reports it.